vue 组件之间的传值

$dispatch 只会通知自己的父亲,父亲的父亲,父亲的父亲

eventBus 所有的父组件和子组件

main.js 全局注册

    // 向上通知
    Vue.prototype.$dispatch = function (eventName,value) {
          let parent = this.$parent
          while(parent) {
           parent.$emit(eventName,value)
            parent = parent.$parent
          }
    }
// 向下传递
Vue.prototype.$broadcast = function (eventName,value) {
  // 获取当前组件下的所有的孩子
  const broadCast = (children) => {
    children.forEach(child => {
      child.$emit(eventName,value)
      if (child.$children) {
        broadCast(child.$children)
      }
    });
  }

  broadCast(this.$children)
}

$attrs表示的是属性的集合

v-bind="$attrs" 传递传过来的所有的值给下一个组件

$listeners表示的是方法的集合

v-on="$listeners" 传递传过来的所有的方法给下一个组件

eventBus 定义到全局上

Vue.prototype.$bus = new Vue()

this.$bus.$on('绑定的事件', function () {

})

this.$bus.$emit('触发绑定的事件',XXX)

 

posted @ 2022-12-20 15:37  杨不凡  阅读(22)  评论(0编辑  收藏  举报