在Vue中使用事件总线EventBus

2,771 阅读1分钟

EventBus的简介

EventBus 又称为事件总线。在Vue中可以使用 EventBus 来做跨组件及兄弟组件通讯

EventBus的使用

在vue中使用EventBus可以分为三步

  1. 在main.js中挂载EventBus
  2. 在A页面发送事件
  3. 在B页面监听事件

挂载EventBus

// main.js文件中
// 通过new Vue 来创建EventBus对象,然后将其挂载到全局
Vue.prototype.$Bus = new Vue()

使用EventBus

在 A 组件中发送事件

// A 组件 文件中
// 通过 this.$Bus.$emit 来发送事件
this.$Bus.$emit('busClick','我是来自A页面的信息')

在 B 组件中监听事件

// B 组件 文件中
// 通过 this.$Bus.$on 来监听EvenBus事件
// 需要注意,需要在vue中生命周期中监听,如在 created 中监听
created() {
    this.$Bus.$on('busClick',(res)=>{
        console.log(res,'监听到了');
    })
}