iview事件处理 dispatch(派发)和broadcast(广播)
什么是dispatch(派发),简单的来说就是寻找指定的父级组件在其身上触发指定事件。
// 组件名、事件名、参数
function dispatch(componentName, eventName, params) {
// 寻找父组件 找不到则返回根组件
let parent = this.$parent || this.$root;
// 返回组件名称
let name = parent.$options.name;
// 寻找指定名称的父组件
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.name;
}
}
// 找到则触发指定的事件
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
},
什么是broadcast(广播),寻找当前组件的指定后代,并且触发自定义事件。
// 组件名、事件名、参数
function broadcast(componentName, eventName, params) {
// 神搜寻找指定的后代
this.$children.forEach(child => {
const name = child.$options.name;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
// todo 如果 params 是空数组,接收到的会是 undefined
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
用图
在vue1.0的时候,也有广播和派发。在2.0中出去了。但是我们在编写复杂组件的时候,还是会用的上的,比如表单验证,当表单元素变更时通知父组件验证。