Vue 兄弟组件之间的通信
Vue 兄弟组件之间的通信
参考:https://blog.csdn.net/weixin_39763493/article/details/107182252
1. Vue中实现兄弟组件的通讯一般为2种方式:
- 一种方法是让父组件允当两个子组件之间的
中间件(中继)
; - 另一种就是使用
EventBus(事件总线)
,它允许两个子组件之间直接通讯,而不需要涉及父组件。
由于中继方式比较简单,这里不做赘述,只讲EventBus
方式。
2. EventBus具体实现
- 首先在main.js文件中定义一个新的
bus
对象并且挂载在原型链上,其实他是一个全新的Vue实例:
Vue.prototype.$bus = new Vue()
- 兄弟组件 a.js 中,声明并监听事件
brotherEvent
created(){
this.$bus.$on('brotherEvent', res=>{
console.log(res) // 得到123
})
}
- 兄弟组件 b.js 中,触发 $bus 中的
brotherEvent
methods:{
bAction(){
this.$bus.$emit('brotherEvent', ’123‘)
}
}