要解决的问题
主要针对组件之间的跨级通信
为什么要自己实现dispatch与broadcast?
因为在做独立组件开发或库时,最好是不依赖第三方库
为什么不使用provide与inject?
因为它的使用场景,主要是子组件获取上级组件的状态,跨级组件间建立了一种主动提供与依赖注入的关系。
然后有两种场景它不能很好的解决:
父组件向子组件(支持跨级)传递数据;
子组件向父组件(支持跨级)传递数据。
代码如下:
emitter.js
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可以监听到
到此这篇关于详解vue之自行实现派发与广播(dispatch与broadcast)的文章就介绍到这了,更多相关vue 派发与广播内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
木头1979