脚本宝典收集整理的这篇文章主要介绍了详解vue之自行实现派发与广播(dispatch与broadcast),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
主要针对组件之间的跨级通信
因为在做独立组件开发或库时,最好是不依赖第三方库
因为它的使用场景,主要是子组件获取上级组件的状态,跨级组件间建立了一种主动提供与依赖注入的关系。
然后有两种场景它不能很好的解决:
父组件向子组件(支持跨级)传递数据;
子组件向父组件(支持跨级)传递数据。
代码如下:
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 派发与广播内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
以上是脚本宝典为你收集整理的详解vue之自行实现派发与广播(dispatch与broadcast)全部内容,希望文章能够帮你解决详解vue之自行实现派发与广播(dispatch与broadcast)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。