全局事件总线

524 阅读1分钟

1.1 作用

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

2.1 基本使用

main.js

//在beforeCreate钩子中给Vue原型绑定全局事件总线$bus (名字随便起,为了直观起名$bus,你叫xxx都行)
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
  beforeCreate () {
    Vue.prototype.$bus=this     //this指向Vue实例对象,所以全局可以访问
  }
})

children1.vue 触发事件,提供数据

<button @click="send">发送</button>
-----------------------------------
methods:{
    send () {
        this.$bus.$emit('hhh',111)  //参数111
    }
}

children2.vue 接收数据

 mounted() {
     this.$bus.$on('hhh',this.demo)  //接收来自$emit的数据
 },
 methods:{
    demo (val) {
         console.log('我接收到了',val)  
    }
},

3.1 注销全局总线

children2.vue

//在接收的组件中调用beforeDestroy钩子,解绑全局事件总线
beforeDestroy() {
    this.$bus.$off('hhh')//注意:要写上解绑的名字。this.$bus.$off()这样写,所以的事件都解绑了,慎用
}

如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/