vue採用EventBus實現跨組件通訊及注意事項

EventBus

EventBus是一種發佈/訂閱事件設計模式的實踐。
在vue中適用於跨組件簡單通訊,不適應用於複雜場景多組件高頻率通訊,相似購物車等場景狀態管理建議採用vuex。javascript

掛載EventBus到vue.prototype

添加bus.js文件
//src/service/bus.jsvue

export default (Vue) => {
  const eventHub = new Vue()
  Vue.prototype.$bus = {
  /**
   * @param {any} event 第一個參數是事件對象,第二個參數是接收到消息信息,能夠是任意類型
   * @method $on  事件訂閱, 監聽當前實例上的自定義事件。https://cn.vuejs.org/v2/api/#vm-on
   * @method $off  取消事件訂閱,移除自定義事件監聽器。  https://cn.vuejs.org/v2/api/#vm-off  https://github.com/vuejs/vue/issues/3399
   * @method $emit  事件廣播, 觸發當前實例上的事件。 https://cn.vuejs.org/v2/api/#vm-emit
   * @method $once  事件訂閱, 監聽一個自定義事件,可是隻觸發一次,在第一次觸發以後移除監聽器。 https://cn.vuejs.org/v2/api/#vm-once
   */
    $on (...event) {
      eventHub.$on(...event)
    },
    $off (...event) {
      eventHub.$off(...event)
    },
    $once (...event) {
      eventHub.$once(...event)
    },
    $emit (...event) {
      eventHub.$emit(...event)
    }
  }
}

註冊
//main.jsjava

import BUS from './service/bus'
BUS(Vue)

注意事項

  1. 事件訂閱($on)必須在事件廣播($emit)前註冊;
  2. 取消事件訂閱($off)必須跟事件訂閱($on)成對出現。

使用場景

  1. 跨路由組件使用eventbus通訊
    假設a路由跳轉b路由須要經過eventbus通訊,先觀察路由跳轉先後a,b組件的生命週期鉤子函數,能夠發現二者是交叉執行的。
    因爲事件訂閱必須在事件廣播前註冊,因此事件訂閱能夠放在b組件beforeCreate,created,beforeMout鉤子函數中,而事件廣播能夠放在a組件的beforeDestroy,destroyed中。
    取消事件訂閱必須跟事件訂閱成對出現,不然會重複訂閱,對javascript性能形成沒必要要的浪費。所以B組件銷燬前需取消當前事件訂閱。

    圖片描述

A組件git

beforeDestroy () {
    //事件廣播
      this.$bus.$emit('testing', color)
    }

B組件github

created () {
    //事件訂閱
      this.$bus.$on('testing', (res) => { console.log(res) })
    },
    beforeDestroy () {
      this.$bus.$off('testing')
    }

2.普通跨組件通訊:因爲兩組件幾乎同時加載,所以建議事件廣播放在created鉤子內,事件訂閱放在mouted中便可。具體使用場景建議在兩組件分別打印生命鉤子函數進行準確判斷。vuex

beforeCreate: function () {
    console.group('A組件 beforeCreate 建立前狀態===============》')
  },
  created: function () {
    console.group('A組件 created 建立完畢狀態===============》')
  },
  beforeMount: function () {
    console.group('x組件 beforeMount 掛載前狀態===============》')
  },
  mounted: function () {
    console.group('x組件 mounted 掛載結束狀態===============》')
  },
  beforeUpdate: function () {
    console.group('x組件 beforeUpdate 更新前狀態===============》')
  },
  updated: function () {
    console.group('x組件 updated 更新完成狀態===============》')
  },
  beforeDestroy: function () {
    console.group('x組件 beforeDestroy 銷燬前狀態===============》')
  },
  destroyed: function () {
    console.group('x組件 destroyed 銷燬完成狀態===============》')
  }
相關文章
相關標籤/搜索