国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

詳解vue之自行實(shí)現(xiàn)派發(fā)與廣播(dispatch與broadcast)

瀏覽:2日期:2022-10-10 13:51:51
要解決的問題

主要針對組件之間的跨級通信

為什么要自己實(shí)現(xiàn)dispatch與broadcast?

因?yàn)樵谧霆?dú)立組件開發(fā)或庫時,最好是不依賴第三方庫

為什么不使用provide與inject?

因?yàn)樗氖褂脠鼍埃饕亲咏M件獲取上級組件的狀態(tài),跨級組件間建立了一種主動提供與依賴注入的關(guān)系。然后有兩種場景它不能很好的解決:父組件向子組件(支持跨級)傳遞數(shù)據(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ù)組,接收到的會是 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)跨級組件自定義通信了,但是,要注意其中一個問題:訂閱必須先于發(fā)布,也就是說先有on再有emit

父子組件渲染順序,實(shí)例創(chuàng)建順序

子組件先于父組件前渲染,所以在子組的mounted派發(fā)事件時,在父組件中的mounte中是監(jiān)聽不到的。而父組件的create是先于子組件的,所以可以在父組件中的create可以監(jiān)聽到

到此這篇關(guān)于詳解vue之自行實(shí)現(xiàn)派發(fā)與廣播(dispatch與broadcast)的文章就介紹到這了,更多相關(guān)vue 派發(fā)與廣播內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 且末县| 喀什市| 光泽县| 武宣县| 中宁县| 枝江市| 仙居县| 涿鹿县| 深圳市| 建水县| 毕节市| 河南省| 嵊州市| 通化市| 民丰县| 正安县| 桓仁| 鄄城县| 申扎县| 正安县| 宿迁市| 陕西省| 沁源县| 西华县| 阳江市| 德化县| 石泉县| 神木县| 龙州县| 鹰潭市| 宿迁市| 太谷县| 曲麻莱县| 林西县| 琼海市| 澎湖县| 武穴市| 武胜县| 嘉义县| 科技| 沅江市|