关于组件通信你必须要理解一件事:事件派发者与监听者是同一个。也就是说谁派发的就由谁监听。
一,事件总线
任意两个组件之间传值常⽤事件总线 或 vuex的⽅式。
1,局部事件总线
main.js:
export var $burVue = new Vue()
childA:
import {$burVue} from '../main'
$parent.$emit('changeFather', 'A')
childB:
import {$burVue} from '../main'
$burVue.$on('changeFather', (data) => {
this.title = data
})
2,全局事件总线
main.js:
Vue.prototype.$burVue = new Vue()
childA:
this.$burVue.$emit('changeFather', 'A')
childB:
this.$burVue.$on('changeFather', (data) => {
this.title = data
})
3,采用发布,订阅原理的全局事件总线
main.js:
var EventBus = new Vue();
Object.defineProperties(Vue.prototype, {
$burVue: {
get: function () {
return EventBus
}
}
})
childA:
this.$burVue.$emit('changeFather', 'A')
childB:
this.$burVue.$on('changeFather', (data) => {
this.title = data
})
4,注意事项
如果使用不善,EventBus 会是一种灾难,到底是什么样的“灾难”了?大家都知道vue是单页应用,如果你在某一个页面刷新了之后,与之相关的EventBus会被移除,这样就导致业务走不下去。还要就是如果业务有反复操作的页面,EventBus 在监听的时候就会触发很多次,也是一个非常大的隐患。这时候我们就需要好好处理 EventBus 在项目中的关系。通常会用到,在vue页面销毁时,同时移除EventBus 事件监听
// 移除特定监听
$burVue.$off('changeFather',{})
// 移除所有监听
$burVue.$off()
只监听一次
$burVue.$once('changeFather', (data) => {
this.title = data
})
二,$parent/$root
childA:
this.$parent.$emit('changeFather', 'A')
或者
this.$root.$emit('changeFather', 'A')
childB:
this.$parent.$on('changeFather', (data) => {
this.title = data
})
或者
this.$root.$on('changeFather', (data) => {
this.title = data
})
三,$children
⽗组件可以通过$children访问⼦组件实现⽗⼦通信。
五,provide/inject
注意:官方说明此种传值方式不是响应式的,但是如果父级给的是动态的也是响应式的