网络编程 发布日期:2024/12/28 浏览次数:1
主要针对组件之间的跨级通信
因为在做独立组件开发或库时,最好是不依赖第三方库
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])); } }); } 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); } } };
parent.vue
<template> <div> <h1>我是父组件</h1> <button @click="handleClick">触发事件</button> <child /> </div> </template> <script> import Emitter from "@/mixins/emitter.js"; import Child from "./child"; export default { name: "componentA", mixins: [Emitter], created() { this.$on("child-to-p", this.handleChild); }, methods: { handleClick() { this.broadcast("componentB", "on-message", "Hello Vue.js"); }, handleChild(val) { alert(val); } }, components: { Child } }; </script>
child.vue
<template> <div>我是子组件</div> </template> <script> import Emitter from "@/mixins/emitter.js"; export default { name: "componentB", mixins: [Emitter], created() { this.$on("on-message", this.showMessage); this.dispatch("componentA", "child-to-p", "hello parent"); }, methods: { showMessage(text) { window.alert(text); } } }; </script>
这样就能实现跨级组件自定义通信了,但是,要注意其中一个问题:订阅必须先于发布,也就是说先有on再有emit
子组件先于父组件前渲染,所以在子组的mounted派发事件时,在父组件中的mounte中是监听不到的。
而父组件的create是先于子组件的,所以可以在父组件中的create可以监听到