发布订阅模式在组件封装中的应用

92 阅读1分钟

问题出现

给组件配置init方法,调用init方法来渲染组件。

xx.init = () => {
  const dom = document.createElement('div');
  dom.setAttribute('id', 'xx');
  new Vue({
    render: (h) => h(xx)
  }).$mount('#xx')
}

这种渲染方法就存在调用方向组件内部传递方法和组件内部向调用方传参的问题。

问题解决

在组件导出的index.js文件,给vue添加一个全局的events属性,

Vue.prototype.events = {
  events: {},
  on: function (eventName, fn) {
    this.events[eventName] = this.events[eventName] || [];
    this.events[eventName].push(fn);
  },
  off: function (eventName, fn) {
    if (this.events[eventName]) {
      for (var i = 0; i < this.events[eventName].length; i++) {
        if (this.events[eventName] === fn) {
          this.events[eventName][i].splice(i, 1);
          break;
        }
      }
    }
  },
  emit: function (eventName, data) {
    if (this.events[eventName]) {
      this.events[eventName].forEach(function (fn) {
        fn(data)
      });
    }
  }
}

在组件内部利用events.on的方式写下想传递的方法

this.events.on(方法名,方法)

调用方利用events.emit的方法调用

this.events.emit(方法名,参数)