vue.js 兄弟組件傳值

一、兄弟之間傳遞數據須要藉助於事件車,經過事件車的方式傳遞數據vue

二、建立一個Vue的實例,讓各個兄弟共用同一個事件機制。app

三、傳遞數據方,經過一個事件觸發bus.$emit(方法名,傳遞的數據)。函數

四、接收數據方,經過mounted(){}觸發bus.$on(方法名,function(接收數據的參數){用該組件的數據接收傳遞過來的數據}),此時函數中的this已經發生了改變,能夠使用箭頭函數。this

實例以下:spa

咱們能夠建立一個單獨的js文件eventVue.js,內容以下 code

import Vue from 'vue'

export default new Vue

假如父組件以下: component

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

子組件a以下: blog

<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這個方法會觸發一個事件
           }
      }
}
</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組件內容"
        }
   },
   created:function(){
       this.bbtn();
   },
   methods:{
       bbtn:function(){
            eventVue .$on("myFun",(message)=>{   //這裏最好用箭頭函數,否則this指向有問題
                 this.btext = message      
            })
       }
    }
}
</script>

這樣在子組件a裏面點擊函數就能夠改變兄弟組件b裏面的值了。ip

相關文章
相關標籤/搜索