全局事件总线

80 阅读1分钟

1、一种组件间的事件通信方式,适用于任意组件间通信。

2、安装全局事件总线:

let vm = new Vue({
  router,
  store,
  render: (h) => h(App),
  beforeCreate(){
      Vue.prototype.$bus=this,//安装全局事件总线,$bus就是当前应用的vm
  },
}).$mount('#app');

3、使用事件总线:

接收数据:A组件想要接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

```A组件
methods:{
    demo(data){
    console.log('我是A组件,我接收到了数据',data)
    }
},

//挂载完毕就给它绑定事件
mounted(){
    this.$bus.$on('hello',this.demo)
},

//最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

beforeDestroy(){
this.$bus.$off('hello') //一定要写解绑的是哪个事件,不写的话,会导致所有绑丁在$bus上的都解绑
}
```

提供数据:B组件提供数据

```B组件
<button @click="sendStudentName">点击发送数据给A组件</button>

methods:{
sendStudentName(){
      this.$bus.$emit{'hello',数据}
  }
}
```