使用EventBus和$on实现全局通信----随笔

2 阅读1分钟

EventBus 是一种常用的方式来实现组件之间的通信。以下是具体步骤:

  1. 创建 EventBus

    main.js 中创建并挂载 EventBus

    javascriptCopy Code
    // main.js
    import Vue from 'vue';
    import App from './App.vue';
    
    export const EventBus = new Vue();
    
    Vue.prototype.$eventBus = EventBus;
    
    new Vue({
      render: h => h(App),
    }).$mount('#app');
    
  2. 触发事件

    在发送事件的组件中,使用 this.$eventBus.$emit 触发事件:

    // SenderComponent.vue
    export default {
      methods: {
        triggerEvent() {
          this.$eventBus.$emit('deptReset');
        }
      }
    };
    
  3. 监听事件

    在接收事件的组件中,使用 this.$eventBus.$on 监听事件:

    export default {
      created() {
      // 注意点,这里写法容易出现犯错的情况,必须按照写法一的方式或写法二的方式,如果写成
        // 错误写法,这里执行方法多了个括号会引起this指向问题
        // this.$eventBus.$on('deptReset', this.handleDeptReset()); 
        // 写法一
        this.$eventBus.$on('deptReset', this.handleDeptReset); 
        // 写法二
        this.$eventBus.$on('deptReset', ()=>{
            this.handleDeptReset()
        });
      },
      beforeDestroy() {
        this.$eventBus.$off('deptReset');
      },
      methods: {
        handleDeptReset() {
          // 执行所需操作
        }
      }
    };