Vue非父子组件传递参数

96
毛宇鹏
2018.05.03 16:24 字数 57

工具类 event.js

var events = {}

function on(name, self, callback) {
  var tuple = [self, callback]
  var callbacks = events[name]
  if (Array.isArray(callbacks)) {
    callbacks.push(tuple)
  } else {
    events[name] = [tuple]
  }
}

function remove(name, self) {
  var callbacks = events[name]
  if (Array.isArray(callbacks)) {
    events[name] = callbacks.filter((tuple) => {
      return tuple[0] !== self
    })
  }
}

function emit(name, data) {
  var callbacks = events[name]
  if (Array.isArray(callbacks)) {
    callbacks.map((tuple) => {
      var self = tuple[0]
      var callback = tuple[1]
      callback.call(self, data)
    })
  }
}

exports.on = on
exports.remove = remove
exports.emit = emit

使用方法

例如:
组件A注册 changeTab 事件, 组件B中, 选择了tab,并主动告知组件A

组件A注册事件

mounted () {
  let that = this
  event.on('selectedTagCallback', this, function(data) {
    // selectedTagCallback: 事件名称
    // data :   回调的参数
  })
}

组件B触发事件

event.emit('selectedTagCallback', data)

组件A销毁事件

event.remove('selectedTagCallback', this)
随笔
Web note ad 1