Vue父组件主动获取子组件数据以及方法
1.在组件上注册引用信息ref
<item ref="children"></item>
2.在父组件上调用
this.$ref.children.data (调用data数据)
this.$ref.children.method() (调用方法)
3.子组件可以使用 $emit 触发父组件的自定义事件。
例如:子组件:
<template>
<div class="train-city">
<h3>父组件传给子组件的toCity:{{parentData}}</h3>
<button @click='send('100')'>点击此处将'ID'发射给父组件</button>
</div>
</template>
<script>
export default {
name:'child',
props:['parentData'], // 用来接收父组件传给子组件的数据
methods:{
send(id) {
this.$emit('sendId',id);//send事件触发后,自动触发sendId事件
}
}
}
</script>
父组件获取子组件事件
<template>
<div>
<div>父组件的toCity{{send}}</div>
<Child @sendId="father" :sendData="send"></Child>
</div>
<template>
<script>
import Child from "./child";
export default {
name:'index',
components: {Child},
data () {
return {
send:"父组件传给子组件的值"
}
},
methods:{
father(id){//触发子组件事件,获取传过来的id
console.log('Child:'+id)
}
}
}
</script>
父组件传值给子组件
子组件通过props接收父组件传过来的值
export default { data () { return { name:'我是子组件里面的数据' } }, methods:{ getParent(){ console.log(this.$parent.title) /*获取整个父组件*/ this.$parent.run()/*获取父组件的方法*/ } }, props:['title','run','home'] /*通过props接收父组件传递过来的数据 */ }
来源:https://www.cnblogs.com/zhou-Blog/p/10535329.html