詳解vue之自行實現派發與廣播(dispatch與broadcast)
主要針對組件之間的跨級通信
為什么要自己實現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 派發與廣播內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
