组件之间的通信方式
- props
- eventbus
- vuex
- 自定义事件
- 属性
- $parent
- $children
- $root
- $refs
- provide/inject
- 非props
- $attr
- $listeners
$parent
用于父组件之间的子组件进行通信
//父组件
<Child1></Child1>
<Child2></Child2>
//child1
this.$parent.emit('say','hello')
//child2
this.$parent.on('say',msg=>{
console.log(msg)//hello
})
//发布订阅的模式,原理和bus相似
$children
父组件通过该属性可以访问到子组件事件(当存在异步组件,组件的顺序不能保证和书写顺序一致)
//父组件
<Child1></Child1>
<Child2></Child2>
<button @click="goHome()"></button>
...
goHome(){
this.$children[0].eat()
}
//child1
methods:{
eat(){
console.log('收到,马上到家')
}
}
$attr
子组件中没有声明props 自动存在该属性中
//父组件
<Child2 msg="Not use props"></Child2>
//子组件child2
<p>{{$attrs.msg}}</p>
...
props:{}
$listeners
在子组件中监听事件,事件的回调函数在父组件中执行,this为父组件的this
//父组件
<Child2 @click="onclick"></Child2>
...
onclick(){
console.log("直接在父组件中执行回调函数")
}
//子组件
//点击标题 监听到外部绑定的点击事件,并执行
<p v-on="$listeners">标题</p>
$ref
通过定义子组件的ref属性,就可以在父组件中访问子组件中的方法和属性
<Child ref="childRef"></Child>
mounted(){
this.$ref.childRef.method1()
this.$ref.childRef.data1='dataValue'
//有一点需要注意的时,确保访问的时候子组件元素已经创建成功,
//必要时可以加nextClick()方法,写在它的回调函数中,来延迟函数的执行
provide/inject
用于祖先到子孙组件的传值,可以跨多层传递,一般用在ui组件库开发中,平时的项目我们可以使用vuex
//祖先
export default{
provide(){
return {
'foo':'this is msg'
}
}
//子孙,一般只进行祖先到子孙的单项数据流,不支持子组件修改数据
<p>{{foo}}</p>
export default{
inject:['foo'],
//inject:{bar:[form:'foo']}//起别名,{{bar}}
}