我們接著上文繼續(xù),本文我們講解兄弟組件的通信,項目結(jié)構(gòu)還是跟上文一樣.
網(wǎng)站的建設(shè)創(chuàng)新互聯(lián)建站專注網(wǎng)站定制,經(jīng)驗豐富,不做模板,主營網(wǎng)站定制開發(fā).小程序定制開發(fā),H5頁面制作!給你煥然一新的設(shè)計體驗!已為成都木屋等企業(yè)提供專業(yè)服務(wù)。
在src/assets目錄下建立文件EventHandler.js,該文件的作用在于給同級組件之間傳遞事件
EventHandler.js代碼:
import Vue from 'Vue'; export default new Vue();
1,在Components目錄下新建一個組件Brother1.vue
<template> <div> <h4>Z國: ghostwu</h4> <input v-on:click="send" type="button" value="發(fā)送"> <p>{{msg}}</p> </div> </template> <script> import EventHandler from '../assets/EventHandler.js'; export default { data(){ return { msg : '' } }, methods : { send(){ EventHandler.$emit( 'myDefineEv', "ghostwu向島國發(fā)射了一顆原子彈" ); } }, mounted (){ let _this = this; EventHandler.$on( "RDefineEv", function( data ){ _this.msg = data; } ); } } </script>
。通過EventHandler.$emit發(fā)送一個自定義事件myDefineEv
。通過mouted【相當(dāng)于jquery的ready, 原生js的onload】,這個是vue生命周期的鉤子函數(shù), 用于在頁面加載完成之后執(zhí)行代碼,在這里就是接收RDefineEv事件( Brother2.vue定義的 )
2,在Components目錄下新建一個組件Brother2.vue
<template> <div> <h4>R國:八嘎</h4> {{msg}} <input v-on:click="defend" type="button" value="防御"> </div> </template> <script> import EventHandler from '../assets/EventHandler.js'; export default { data(){ return { msg : '' } }, methods : { defend(){ EventHandler.$emit( 'RDefineEv', "島國采用了高科技反原子彈系統(tǒng)" ); } }, mounted(){ let _this = this; EventHandler.$on( "myDefineEv", function( data ){ _this.msg = data; } ); } } </script>
。點擊按鈕發(fā)送RDefineEv事件
。文檔ready的時候,接收myDefineEv(Brother1.vue)出發(fā)的自定義事件
三、在App.vue中調(diào)用兩個同級組件
<template> <div id="app"> <Brother1></Brother1> <Brother2></Brother2> </div> </template> <script> import Brother1 from './components/Brother1.vue'; import Brother2 from './components/Brother2.vue'; export default { components : { Brother1, Brother2 } } </script>
小結(jié):
創(chuàng)建一個事件傳遞中心,例如EventHandler.js,用它作為傳遞消息的中介
在需要傳值的組件中用EventHandler.$emit觸發(fā)一個自定義事件,并傳遞參數(shù)
在需要接收數(shù)據(jù)的組件中用EventHandler.$on監(jiān)聽自定義事件,并在回調(diào)函數(shù)中處理傳遞過來的參數(shù)
以上這篇Vue2.0基于vue-cli+webpack同級組件之間的通信教程(推薦)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持創(chuàng)新互聯(lián)。
網(wǎng)頁題目:Vue2.0基于vue-cli+webpack同級組件之間的通信教程(推薦)
本文URL:http://sd-ha.com/article2/iecooc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計公司、商城網(wǎng)站、網(wǎng)站收錄、標(biāo)簽優(yōu)化、自適應(yīng)網(wǎng)站、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)