Vue2中全局事件总线
1、一种组件间通信的方式 ,适用于任意组件间的通信
2、安装全局事件总线(vue2可用,vue3已废弃)
//创建vm
new Vue({
el:‘#app’,
render:h=>h(App),
beforeCreate(){
Vue.prototype.$bus=this //安装全局事件总线
}
})
3、使用事件总线
1、接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
methods(){
demo(data){
//代码
}
},
mounted(){
this.$bus.$on('xxx',this.demo) //对xxx事件进行绑定,调用demo方法
}
或者直接demo()方法写到mounted中如下
......
mounted(){
this.$bus.$on('xxx',(data)=>{
//console.log(data) //具体方法
}) //对xxx事件进行绑定,调用demo方法
}
2、提供数据:
sendData(){
this.$bus.$emit('xxx',数据)
}
4、解绑事件
最好在beforeDestroy钩子函数中,用$off去解绑当前组件所用到的事件