vue里面的eventBus使用

  1. // eventBus.js
  2. export default new Vue();
  3. // on.js
  4. import eventBus from './eventBus.js'
  5. eventBus.$on(test, function(val) {
  6. console.log(val); // string
  7. })
  8. // emit.js
  9. import eventBus from './eventBus.js'
  10. eventBus.$emit(test, 'string');

本质是发布订阅模式

  1. class EventBus {
  2. constructor() {
  3. this.callback = {};
  4. }
  5. $on(name, fn) { // 订阅
  6. this.callback[name] = this.callback[name] || []; // 需要在多个地方订阅,所以需要使用数据
  7. this.callback[name].push(fn);
  8. }
  9. $emit(name, ...args) { // 发布
  10. if (this.callback[name]) {
  11. this.callback[name].forEach(fn => {
  12. fn(...args)
  13. })
  14. }
  15. }
  16. }

发布订阅步骤

  1. 首先创建一个类,里面有一个callback对象
  2. 创建订阅方法,参数为订阅名称和具体执行的函数
    1. 然后把订阅名称作为callback对象的对象名