全局事件总线是一种组件间能够互相进行通信的方式。
安装全局事件总线
首先要在main,js 在创建Vue实例对象中beforeCreate钩子里面进行配置,之所以在这个钩子里配置是因为beforeCreate 时还未对数据监测、数据代理等进行挂载。
我们通过Vue.prototype.$bus = this,将Vue的原型对象的属性$bus指向当前的Vue实例对象,从而实现Vue实例对象和VueComponent实例对象都可以访问到Vue原型对象上的$on,$emit,$off,方法了。
new Vue({
//配置全局总线
beforeCreate() {
Vue.prototype.$bus = this
},
render: h => h(App),
router,
store
}).$mount('#app')
使用
1.接收数据
mounted() {
//getName是发送方所绑定的事件名,value是接收到的数据
this.$bus.$on('getName', (value)=>{
console.log(value)
})
}
2.发送数据
methods:{
send(){
this.$bus.$emit('getName',this.name)
}
}
3.解绑
最好在beforeDestroy钩子中,用$off去解绑当前组件用到的事件,因为
$bus
会一直存在,若不解绑,则会一直占用着总线上的某个方法,导致别的组件调用同名方法时,会出现冲突。
mounted() {
//getName是发送方所绑定的事件名,value是接收到的数据
this.$bus.$on('getName', (value)=>{
console.log(value)
})
}
beforeDestroy() {
this.$off('getName')
}