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. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法2. WMLScript的語(yǔ)法基礎(chǔ)3. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問(wèn)題……4. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問(wèn)題5. html小技巧之td,div標(biāo)簽里內(nèi)容不換行6. xml中的空格之完全解說(shuō)7. XML入門(mén)的常見(jiàn)問(wèn)題(四)8. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)9. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法10. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享
