Commit ef31e98b by member

Update 2.vue单元测试和组件通信(石瑶).md

parent 316e5663
### 主
### 主
......@@ -102,9 +102,99 @@ describe('HelloWorld.vue', () => {
})
done()
})
});
```
### 组件通信
主要介绍跨级的通信方法。 子传祖先和祖先传子孙。$on和$emit 联合起来使用。
this.$emit 触发的自定义事件,然后在父组件上面监听这个自定义事件。这里看似是在父组件处理自定义事件
但是是在子组件上面触发的。所以我们完全可以在祖先组件上监听。
```
<template>
<div class="child" @click="handleClick">
我是子组件
</div>
</template>
<script>
export default {
name: 'child',
methods: {
handleClick() {
this.$emit('on-message', 'ee');
}
},
mount() {
this.$on('on-message', (text) => {
console.log(text);
});
},
};
</script>
```
类似上面的代码 我就可以在子孙组件找到祖先元素,然后触发自定义事件,在祖先组件里面监听自定义事件。
```
/**
* @param { 组件名 } componentName
* @param { 事件名 } eventName
* @param { 参数 } params
*/
function broadcast(componentName, eventName, params) {
this.$children.forEach(child => {
const name = child.$options.name;
if (name === componentName) {
child.$emit.apply(child, [eventName, params]);
} else {
broadcast.apply(child, [componentName, eventName].concat(params));
}
});
}
export default {
methods: {
// 派发 向上查找
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(componentName, eventName, params) {
broadcast.call(this, componentName, eventName, params);
}
}
};
```
从上面的代码中 我看还可以自己扩展相关的方法。如果大家感兴趣,自己能够去实现一下。
```
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment