vue採納EventBus完成跨組件通訊及注意事項

EventBus

EventBus是一種宣布/定閱事宜設想形式的實踐。
在vue中適用於跨組件簡樸通訊,不適應用於龐雜場景多組件高頻率通訊,相似購物車等場景狀況治理髮起採納vuex。

掛載EventBus到vue.prototype

增加bus.js文件
//src/service/bus.js

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.js

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組件燒毀前需作廢當前事宜定閱。

    《vue採納EventBus完成跨組件通訊及注意事項》

A組件

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

B組件

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

2.一般跨組件通訊:因為兩組件險些同時加載,因而發起事宜播送放在created鈎子內,事宜定閱放在mouted中即可。詳細運用場景發起在兩組件離別打印性命鈎子函數舉行正確推斷。

  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 燒毀完成狀況===============》')
  }
    原文作者:菠蘿油王子
    原文地址: https://segmentfault.com/a/1190000015289050
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞