vue-原創(chuàng)-《vue中兄弟組件的傳值》

參考:
https://www.cnblogs.com/xiaotanke/p/7427636.html
https://blog.csdn.net/a15088712506/article/details/78967937

vue中,父子組件的傳值常見,方法也很簡(jiǎn)單,兄弟組件之間的傳值稍微復(fù)雜一些,用的也少,在此備忘。

【一】普通方法

1、兄弟之間傳遞數(shù)據(jù)需要借助于事件車,通過事件車的方式傳遞數(shù)據(jù)
2、創(chuàng)建一個(gè)Vue的實(shí)例,讓各個(gè)兄弟共用同一個(gè)事件機(jī)制。
3、傳遞數(shù)據(jù)方,通過一個(gè)事件觸發(fā)bus.emit(方法名,傳遞的數(shù)據(jù))。 4、接收數(shù)據(jù)方,通過mounted(){}觸發(fā)bus.on(方法名,function(接收數(shù)據(jù)的參數(shù)){用該組件的數(shù)據(jù)接收傳遞過來的數(shù)據(jù)}),此時(shí)函數(shù)中的this已經(jīng)發(fā)生了改變,可以使用箭頭函數(shù)。

實(shí)例如下:
我們可以創(chuàng)建一個(gè)單獨(dú)的js文件event.js,內(nèi)容如下

import Vue from 'vue'
export default new Vue

假如父組件如下:

<template>
     <components-a></components-a>
     <components-b></components-b>
</template>

子組件a如下:

<template>
      <div class="components-a">
           <button @click="abtn">A按鈕</button>
      </div>
</template>
<script>
import eventVue from '../../js/event.js'
export default {
      name: 'app',
      data () {
        return {
                ‘msg':"我是組件A"
        }
      },
      methods:{
           abtn:function(){
                   eventVue.$emit("myFun",this.msg)   //$emit這個(gè)方法會(huì)觸發(fā)一個(gè)事件
           }
      }
}
</script>

子組件b如下:

<template>
     <div class="components-a">
         <div>{{btext}}</div>
     </div>
</template>
<script>
import eventVue from '../../js/event.js'
export default {
   name: 'app',
   data () {
        return {
           'btext':"我是B組件內(nèi)容"
        }
   },
   created:function(){
       this.bbtn();
   },
   methods:{
       bbtn:function(){
            eventVue.$on("myFun",(message)=>{   //這里最好用箭頭函數(shù),不然this指向有問題
                 this.btext = message      
            })
       }
    }
}
</script>

這樣在子組件a里面點(diǎn)擊函數(shù)就可以改變兄弟組件b里面的值了。

【二】方法一的變種

省略了外部的js文件,直接把總線放在main.js里的vue實(shí)例中,寫法如下

new Vue({
    el: "#app",
    router,
    data: {
        eventVue: new Vue()
    },
    template: "<App/>"
    compnents: {App}
})

在使用的時(shí)候,不需要引入外部文件,只需要在Bus前加this.$root,即可調(diào)用。

子組件a:

methods:{
   abtn: function(){
           this.$root.eventVue.$emit("myFun",this.msg)   //$emit這個(gè)方法會(huì)觸發(fā)一個(gè)事件
   }
}

子組件b:

methods:{
   bbtn:function(){
        this.$root.eventVue.$on("myFun",(message)=>{   //這里最好用箭頭函數(shù),不然this指向有問題
             this.btext = message      
        })
   }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容