00 前言
$dispatch 和 $broadcast 作為一對情侶 💑屬性,在 Vue 1.0 中主要用來實(shí)現(xiàn)基于組件樹結(jié)構(gòu)的事件流通信 —— 通過向上或向下以冒泡的形式傳遞事件流,以實(shí)現(xiàn)嵌套父子組件的通信。但是由于其顯功能缺陷,在 Vue 2.0 中就被移除了。雖然 Vue 官網(wǎng)已經(jīng)不再支持使用 $dispatch 和 $broadcast 進(jìn)行組件通信,但是在很多基于 Vue 的 UI 框架中都有對其的封裝,包括 element-ui、iview 等等。
那么 $dispatch 和 $broadcast 到底是怎么工作,其底層又是怎么實(shí)現(xiàn)的呢?接下來,我們就詳細(xì)的說一說!
01 $dispatch 詳解
為了追根溯源,我們還是先去 Vue 1.0 的文檔你觀摩一下其概念吧!
概念:
Dispatch an event, first triggering it on the instance itself, and then propagates upward along the parent chain. The propagation stops when it triggers a parent event listener, unless that listener returns true. Any additional arguments will be passed into the listener's callback function.
上面的一段英文定義來自 Vue 1.0 官方文檔,其大致的意思是說:dispatch 是一個事件,首先會在自己實(shí)例本身上觸發(fā),然后沿父鏈向上傳播。當(dāng)它觸發(fā)父組件上的事件偵聽器時傳播即會停止,除非該偵聽器返回 true。 任何其他參數(shù)都將傳遞給偵聽器的回調(diào)函數(shù)。
參數(shù):
dispatch 會接收兩中參數(shù):event 是事件名稱,[...args] 是觸發(fā)事件時傳遞給回調(diào)函數(shù)的參數(shù)。
**例子:
// 創(chuàng)建一個 parent 組件 var parent = new Vue(); // 創(chuàng)建一個 child1 組件,其父組件指向 parent var child1 = new Vue({ parent: parent }); // 創(chuàng)建一個 child2 組件,其父組件指向 child1 var child2 = new Vue({ parent: child1 }); // 在 parent 組件監(jiān)聽名為 test 的事件,并綁定了一個回調(diào)函數(shù) parent.$on('test', function () { console.log('parent notified'); }); // 在 child1 組件監(jiān)聽名為 test 的事件,并綁定了一個回調(diào)函數(shù) child1.$on('test', function () { console.log('child1 notified'); }); // 在 child2 組件監(jiān)聽名為 test 的事件,并綁定了一個回調(diào)函數(shù) child2.$on('test', function () { console.log('child2 notified'); });
網(wǎng)頁標(biāo)題:Vue中的情侶屬性$dispatch和$broadcast詳解-創(chuàng)新互聯(lián)
文章鏈接:http://jinyejixie.com/article4/disiie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、網(wǎng)站建設(shè)、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站營銷、動態(tài)網(wǎng)站、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容