全局事件总线(GlobalEventBus)

全局事件总线(GlobalEventBus)

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

  2. 安装全局事件总线

    new Vue({
        .....
        beforCreate() {
        	Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	}
    })
    
  3. 使用事件总线:

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

      methods() {
          demo(data) {
              .....
          }
      }
      ........
      mounted() {
          this.$bus.$on('xxxx', this.data)
      }
      
    2. 提供数据:this.$bus.$off('xxxx', 数据)

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

posted @ 2022-01-22 06:14  HuangBingQuan  阅读(373)  评论(0编辑  收藏  举报