[Vue] Use of global event bus (EventBus)

全局事件总线(EventBus)适用于任意组件通信,常用于兄弟之间或者是没有关系的组件之间

Register event bus

main.js

//方式一
new Vue({
    
    
  ···
  beforeCreate(){
    
    
    Vue.prototype.$bus = this
  },
 ···
})
//方式二
new Vue({
    
    
  ···
  beforeCreate(){
    
    
    window.EventBus = new Vue();
  },
 ···
})

use

//在需要传值的地方用
//方式一
this.$bus.$emit("userInfo", this.userInfo);  //也可以传单个值
//方式二
EventBus.$emit('userInfo', param1,param2,...)

take over

//方式一
this.$bus.$on('userInfo', (userInfo)=>{
    
    
    console.log(userInfo)
})
//方式二
EventBus.$on('userInfo', (param1,param2,...)=>{
    
    
    console.log(param1,param2,...)
})

Destroy the event bus

//方式一
beforeDestroy(){
    
    
  this.$bus.$off('自定义事件名') 
  //例如this.$bus.$off('userInfo') 
}
//方式二
beforeDestroy(){
    
    
  EventBus.$off('自定义事件名');
  //例如EventBus.$off('userInfo');
}

Notice

It is best to destroy it in beforeDestroy after use

Guess you like

Origin blog.csdn.net/qq_44862029/article/details/125661218