vue组件库封装 广播 $dispatch $broadcast
作者:互联网
$dispatch和$broadcast源代码:
function broadcast (componentName, eventName, params) { this.$children.forEach(child => { const name = child.$options.name // 组件名与传入componentName一致 if (name === componentName) { // 子组件触发eventName事件 child.$emit.apply(child, [eventName].concat(params)) } else { broadcast.apply(child, [componentName, eventName].concat([params])); // eslint-disable-line } }) } export default { methods: { // 向上触发事件 $dispatch (componentName, eventName, params) { // 获取父实例 let parent = this.$parent || this.$root // 获取组件名 let name = parent.$options.name // 递归查找与componentName一致的组件名 while (parent && (!name || name !== componentName)) { parent = parent.$parent if (parent) { name = parent.$options.name } } if (parent) { // 组件触发eventName事件 parent.$emit.apply(parent, [eventName].concat(params)) } }, // 向子(孙)组件发送事件 $broadcast (componentName, eventName, params) { broadcast.call(this, componentName, eventName, params) } } }
标签:eventName,vue,name,parent,componentName,dispatch,broadcast,params 来源: https://www.cnblogs.com/mengfangui/p/12629173.html