vue小知识:多层数据双向相应之向上派发和向下派发($dispatch和$broadcast)
注意:这两个实例已经在vue3中弃用啦!!!(所以不详细说了,封装知道怎么用就行了,作为了解)
都是在vue实例配置(main.js)
向上派发:$dispatch
注意,在相应后代组件中使用
this.$dispatch(eventName, value);
表示向上派发事件,只要其祖先元素上有该事件,都会被触发。
配置main,js:
Vue.prototype.$dispatch=function(eventName,value){
let parent =this.$parent
while(parent){
parent.$emit(eventName,value)
parent=parent.$parent
}
}
向下派发:$broadcast
表示该组件的后代组件都会触发该派发的事件
配置:main.js
Vue.prototype.$broadcast=function(eventName,vlaue){
let broadcast=()=>{
this.$children.forEach(child => {
child.$emit(eventName,vlaue)
if(child.$children){
broadcast(child.$children)
}
});
}
broadcast();
}
使用:在对应的组件内触发调用:
this.$broadcast(eventName, value);
就是在对应的组件内的相关方法使用条语气,会触发该组件内后代组件eventName名对应的方法。


浙公网安备 33010602011771号