??首先蒜胖,element-ui中的dispatch是用于派發(fā)事件到父組件以及更上級(jí)別的指定組件進(jìn)行接收的。而broadcast方法主要用于將數(shù)據(jù)或者方法廣播到子組件以及子孫指定組件進(jìn)行接收抛蚤。這兩個(gè)方法原理如下圖所示台谢。
.src/mixins/emitter.js
/**
* 廣播方法定義
* @param String componentName 組件名稱
* @param String eventName 事件名稱
* @param Object params 參數(shù)
*/
function broadcast(componentName, eventName, params) {
// 遍歷子組件,對(duì)子組件的name進(jìn)行匹配
this.$children.forEach(child => {
var name = child.$options.componentName;
// 當(dāng)子組件中的名稱匹配到傳入的componentName時(shí)岁经,在子組件中傳入該事件并傳遞params
if (name === componentName) {
// 子組件中與傳入的componentName相等時(shí)朋沮,則在子組件中執(zhí)行eventName方法,參數(shù)為params
child.$emit.apply(child, [eventName].concat(params));
} else {
// 如果不存在則繼續(xù)執(zhí)行broadcast方法缀壤,this指向子組件
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
export default {
methods: {
dispatch(componentName, eventName, params) {
// 定義父組件對(duì)象樊拓,如果該組件上面沒(méi)有對(duì)象,則parent為根組件
var parent = this.$parent || this.$root;
var name = parent.$options.componentName; // 父組件名稱
// 當(dāng)父組件對(duì)象存在時(shí)且父組件名稱不等于componentName時(shí)塘慕,則改變parent值筋夏,并將parent值向上賦值;當(dāng)parent不存在或者name === componentName時(shí)图呢,跳出循環(huán)
while (parent && (!name || name !== componentName)) {
parent = parent.$parent; // parent向上賦值
// 如果parent存在(即之前的parent含有$parent時(shí))
if (parent) {
name = parent.$options.componentName;
}
}
// name === componentName時(shí)条篷,則在改組件中執(zhí)行eventName方法骗随,參數(shù)為params
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
},
broadcast(componentName, eventName, params) {
broadcast.call(this, componentName, eventName, params);
}
}
};
??從emitter.js中可以看出,broadcast方法是通過(guò)判斷子組件中是否與componentName相等赴叹,如果相等的話鸿染,則在該組件中通過(guò)Vue自帶的$$emit執(zhí)行eventName方法,參數(shù)為params稚瘾。如果不相等牡昆,則繼續(xù)輪詢。直到不存在子組件為止摊欠。而dispatch事件則是通過(guò)while對(duì)當(dāng)前組件以及當(dāng)前組件名稱是否等于componentName來(lái)進(jìn)行遍歷丢烘。直到當(dāng)前節(jié)點(diǎn)為根節(jié)點(diǎn)或者當(dāng)前組件名稱等于componentName,則跳出循環(huán)。當(dāng)前組件名稱等于componentName些椒,則通過(guò)$emit執(zhí)行eventName,參數(shù)為params播瞳。