vue非父子组件传值之发布订阅模式

vue非父子组件传值之发布订阅模式

目前了解的组件传值的几种方式

  1. props 再熟悉不过了
  2. vuex 也比较常用
  3. evenbus
  4. 发布订阅
    主要说一下发布订阅

Vue.prototype.bus = new Vue();

vue非父子组件传值之发布订阅模式
vue非父子组件传值之发布订阅模式

其实优化一下,也可以这样

Vue.prototype.$subscribe = subscribe
Vue.prototype.$publish = publish
let eventHub = new Vue()
function publish(key, ...args) {

  eventHub.$emit(key, ...args)

  return this
}
function subscribe(key, callback) {

  eventHub.$on(key, callback.bind(this))

  return this
}