Vue兩個同級組件傳值實現(xiàn)
Vue組件之間是有聯(lián)系的,避免不了組件之間要互相傳值,父給子使用v-bind綁定自定義屬性和使用props來接受
子給父使用@自定義事件=’函數(shù)’ this.$emit(’自定義事件’,’要發(fā)送的內(nèi)容’),子組件通過$emit來觸發(fā)父組件的函數(shù)來實現(xiàn)但是兩個同級組件之間這么互相傳值
<div id=’app’> <children1></children1> <children2></children2></div><script> var children1 = {}; var children2 = {}; var vm = new Vue({ el:’#app’, components:{ children1, children2 } })</script>
現(xiàn)在要將children1組件中的數(shù)據(jù)傳給children2組件
主要使用到vue實例中的$on()和$emit()
<div id=’app’> <children1></children1> <children2></children2> </div> <script> var Event = new Vue({}); // 創(chuàng)建一個vue實例用來作為傳值的媒介 var children1 = { template:` <div> <button @click=’send’>點我給children2組件發(fā)送數(shù)據(jù)</button> </div> `, data(){ return { msg:’我是要給children2發(fā)送的數(shù)據(jù)’ } }, methods:{ send(){ Event.$emit(’go’,this.msg) } } }; var children2 = { template:` <div> <h2>從children1組件接收到的值:{{msg1}}</h2> </div> `, data(){ return{ msg1:’’ } }, created(){ Event.$on(’go’,(v) => { // 必須使用箭頭函數(shù)因為this this.msg1 = v; }) } }; var vm = new Vue({ el:’#app’, components:{ children1, children2 } })</script>
chilren1組件要發(fā)送數(shù)據(jù)使用的是Event.$emit()chilren2組件要接收數(shù)據(jù)使用Eevent.$on()
到此這篇關(guān)于Vue兩個同級組件傳值實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue 同級組件傳值內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程2. asp.net core項目授權(quán)流程詳解3. html中的form不提交(排除)某些input 原創(chuàng)4. js select支持手動輸入功能實現(xiàn)代碼5. CSS3中Transition屬性詳解以及示例分享6. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼7. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式8. 開發(fā)效率翻倍的Web API使用技巧9. jsp文件下載功能實現(xiàn)代碼10. ASP常用日期格式化函數(shù) FormatDate()
