关于vue组件通讯

我记得我写过这个逻辑,就是在vue 的原型上加个全局的分发器,然后大家都可以很开心的使用

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

class Bus {
  constructor() {
    this.callbacks = {}
  }

  on(name, fn) {
    this.callbacks[name] = this.callbacks[name] || [];
    this.callbacks[name].push(fn);
  }

  emit(name, args) {

    if (this.callbacks[name]) {
      this.callbacks[name].forEach(cb => {
        cb(args)
      })
    }
  }

}
Vue.prototype.$bus = new Bus();
new Vue({
  render: h => h(App)
}).$mount('#app')


具体使用就简单了

一个发送事件,一个接受事件,这样就可以实现在任何 组件间进行数据传递,

说白了就java 中的 观察者模式

我们继续复习下插槽的知识

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/107505592