全局事件总线(EventBus)适用于任意组件通信,常用于兄弟之间或者是没有关系的组件之间
注册事件总线
main.js
//方式一
new Vue({
···
beforeCreate(){
Vue.prototype.$bus = this
},
···
})
//方式二
new Vue({
···
beforeCreate(){
window.EventBus = new Vue();
},
···
})
使用
//在需要传值的地方用
//方式一
this.$bus.$emit("userInfo", this.userInfo); //也可以传单个值
//方式二
EventBus.$emit('userInfo', param1,param2,...)
接收
//方式一
this.$bus.$on('userInfo', (userInfo)=>{
console.log(userInfo)
})
//方式二
EventBus.$on('userInfo', (param1,param2,...)=>{
console.log(param1,param2,...)
})
销毁事件总线
//方式一
beforeDestroy(){
this.$bus.$off('自定义事件名')
//例如this.$bus.$off('userInfo')
}
//方式二
beforeDestroy(){
EventBus.$off('自定义事件名');
//例如EventBus.$off('userInfo');
}
注意
使用完最好要在beforeDestroy中销毁