詳解vue之自行實(shí)現(xiàn)派發(fā)與廣播(dispatch與broadcast)
主要針對(duì)組件之間的跨級(jí)通信
為什么要自己實(shí)現(xiàn)dispatch與broadcast?因?yàn)樵谧霆?dú)立組件開發(fā)或庫(kù)時(shí),最好是不依賴第三方庫(kù)
為什么不使用provide與inject?因?yàn)樗氖褂脠?chǎng)景,主要是子組件獲取上級(jí)組件的狀態(tài),跨級(jí)組件間建立了一種主動(dòng)提供與依賴注入的關(guān)系。然后有兩種場(chǎng)景它不能很好的解決:父組件向子組件(支持跨級(jí))傳遞數(shù)據(jù);子組件向父組件(支持跨級(jí))傳遞數(shù)據(jù)。
代碼如下:
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 是空數(shù)組,接收到的會(huì)是 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'>觸發(fā)事件</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>
這樣就能實(shí)現(xiàn)跨級(jí)組件自定義通信了,但是,要注意其中一個(gè)問(wèn)題:訂閱必須先于發(fā)布,也就是說(shuō)先有on再有emit
父子組件渲染順序,實(shí)例創(chuàng)建順序子組件先于父組件前渲染,所以在子組的mounted派發(fā)事件時(shí),在父組件中的mounte中是監(jiān)聽不到的。而父組件的create是先于子組件的,所以可以在父組件中的create可以監(jiān)聽到
到此這篇關(guān)于詳解vue之自行實(shí)現(xiàn)派發(fā)與廣播(dispatch與broadcast)的文章就介紹到這了,更多相關(guān)vue 派發(fā)與廣播內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備