UNPKG

1.26 kBJavaScriptView Raw
1/**
2 * @description 跨组件通信库
3 * @author SoldierAb
4 * @since 18-12-28
5 * @example
6 *
7 * child.vue:
8 * this.dispatch('parent',eventName,params);
9 *
10 * parant.vue
11 * this.$on(eventName,params=>{
12 *
13 * });
14*/
15
16
17const broadcast = (componentName, eventName, params) => {
18 this.$children.forEach(child => {
19 const name = child.$options.name;
20 if (name === componentName) {
21 child.$emit.apply(child, [eventName].concat(params));
22 } else {
23 //如果 params 是空数组,接收到的会是 undefined
24 broadcast.apply(child, [componentName, eventName].concat([params]));
25 }
26 });
27}
28export default {
29 methods: {
30 dispatch(componentName, eventName, params) {
31 let parent = this.$parent || this.$root;
32 let name = parent.$options.name;
33
34 while (parent && (!name || name !== componentName)) {
35 parent = parent.$parent;
36 if (parent) name = parent.$options.name;
37 }
38 if (parent) parent.$emit.apply(parent, [eventName].concat(params));
39 },
40 broadcast(componentName, eventName, params) {
41 broadcast.call(this, componentName, eventName, params);
42 }
43 }
44};
\No newline at end of file