Vue兩個(gè)同級(jí)組件傳值實(shí)現(xiàn)
Vue組件之間是有聯(lián)系的,避免不了組件之間要互相傳值,父給子使用v-bind綁定自定義屬性和使用props來(lái)接受
子給父使用@自定義事件=’函數(shù)’ this.$emit(’自定義事件’,’要發(fā)送的內(nèi)容’),子組件通過(guò)$emit來(lái)觸發(fā)父組件的函數(shù)來(lái)實(shí)現(xiàn)但是兩個(gè)同級(jí)組件之間這么互相傳值
<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實(shí)例中的$on()和$emit()
<div id=’app’> <children1></children1> <children2></children2> </div> <script> var Event = new Vue({}); // 創(chuàng)建一個(gè)vue實(shí)例用來(lái)作為傳值的媒介 var children1 = { template:` <div> <button @click=’send’>點(diǎn)我給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ù)因?yàn)閠his 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兩個(gè)同級(jí)組件傳值實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue 同級(jí)組件傳值內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML實(shí)體注入深入理解2. XML入門的常見問(wèn)題(三)3. WMLScript腳本程序設(shè)計(jì)第1/9頁(yè)4. Xpath語(yǔ)法格式總結(jié)5. XML 非法字符(轉(zhuǎn)義字符)6. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂(lè)代碼7. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)8. 不要在HTML中濫用div9. 利用CSS3新特性創(chuàng)建透明邊框三角10. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera
