vue 事件总线eventBus的使用详解

因为在自己的项目不需要类似Vuex这样的库来处理组件之间的数据通信,所以使用了事件总线存储了电话进线的数据,反复操作之后,导致内存暴涨,页面卡死,所以使用该方法的时候要特别注意,特此记录一下. 

使用场景:非父组件通信时,可以向该中心注册发送事件或接收事件,需要的到总线取值就行

注意点:该方法使用起来虽然方便,但EventBus 在监听的时候就会触发很多次,是一个非常大的隐患。一般在项目中会在vue页面销毁时,同时移除EventBus 事件监听.下面会给出发消息——接收消息——移除监听详细流程

借鉴文章:https://my.oschina.net/u/2518341/blog/2960762

1.在项目中新建event-bus.js

const install = function (Vue) {
  const Bus = new Vue({
    methods: {
      emit(event, ...args) {
        this.$emit(event, ...args);
      },
      on(event, callback) {
        this.$on(event, callback);
      },
      off(event, callback) {
        this.$off(event, callback);
      }
    }
  });
  Vue.prototype.$EventBus = Bus;
};
export default install;

2.mian.js 中引入

import VueBus from './event-bus'
Vue.use(VueBus);

3.发送消息

this.$EventBus.$on("aMsg", this.timerFun);
methods: {
    timerFun () {
      this.timer = new Date().getTime()
    }
}

4.接收消息

 this.$EventBus.$on("aMsg", this.getWorkOrderListInfo);

 this.getWorkOrderListInfo是我自己页面写的方法

5.移除监听

强调:特别重要,切记一定要在vue页面销毁的时候移除监听的事件

 beforeDestroy () {
    this.$EventBus.off('aMsg', this.getWorkOrderListInfo);
  },

 文章如有不足,还望指教,谢谢

 

猜你喜欢

转载自www.cnblogs.com/cjechenjinge-0820/p/12982697.html