Vue組件之間數據交互與通信


Vue 的組件作用域都是孤立的,不允許在子組件的模板內直接引用父組件的數據。必須使用特定的方法才能實現組件之間的數據傳遞。

 

一、父組件向子組件傳遞數據

在 Vue 中,可以使用 props 向子組件傳遞數據。

子組件部分:

如果需要從父組件獲取  username  的值,就需要

props:{
   username:{
      type:String
   }
}

示例代碼

<template>
  <div class="child01">
    my name is {{username}}
  </div>
</template>
<script>
export default {
  name: 'child01',
  props:{
    username:{
      type:String
    }
  }
}
</script>

在 props 中添加了元素之后,就不需要在 data 中再添加變量啦。

 父組件部分:

示例代碼

<template>
  <div class="child01">
      <child-box :username="zuobaiquan"></child-box>
  </div>
</template>
<script>
import childBox from './child.vue'
export default {
  name: 'child01',
  data () {
    return {
      zuobaiquan:'zuobaiquan'
    }
  },
  components:{
    'child-box':childBox
  }
}
</script>

 

二、子組件向父組件傳遞數據

一般情況下,子組件主要通過事件傳遞數據給父組件

子組件部分:

示例代碼

<template>
  <ul class="tab-list">
    <li class="tab-li"
      v-for="(item, index) in tabItem"
      v-html="item"
      :class="{active: index === actIndex}"
      @click="handelSwitch(index)"
    >
    </li>
  </ul>
</template>
<script>
export default {
  name: 'child02',
  data(){
    return {
      tabItem:['選項一','選項二','選項三'],
      actIndex:0
    }
  },
  methods:{
    handelSwitch(index){
      this.actIndex=index;
      this.$emit("transferTabIndex",this.actIndex)
    }
  }
}
</script>

這是選項卡子組件,當tabItem的index值發生變化的時候,將 對應的tab的索引index傳遞給父組件

首先聲明一個了方法 handelSwitch,通過點擊事件click來調用 handelSwitch,在 handelSwitch方法中,使用了 $emit 來遍歷 transferTabIndex事件,並傳遞 this.actIndex,

其中 transferTabIndex是一個自定義的事件,功能類似於一個中轉站,可以把this.actIndex通過這個事件傳遞給父組件 

父組件部分:

在父組件parent.vue 中,聲明了一個方法 getTabIndex,用 transferTabIndex事件調用 handelSwitch方法,獲取到從子組件傳遞過來的參數 this.actIndex,傳遞過來的this.actIndex 可以實現 選項卡的div模塊的顯示與隱藏。

  注意:

  如果無需傳遞參數,直接寫成   this.$emit(方法名);

  如果是一個參數,直接以追加參數即可;

  如果是多個參數,直接對象形式或者數組格式傳遞。

示例代碼

<template>
  <div class="child02">
      <child-box @transferTabIndex="getTabIndex"></child-box>
      <div v-show="showIndex==0">我的選項卡1</div>
      <div v-show="showIndex==1">我的選項卡2</div>
      <div v-show="showIndex==2">我的選項卡3</div>
  </div>
</template>
<script>
import childBox from './child.vue'
export default {
  name: 'child02',
  data () {
    return {
      showIndex:0
    }
  },
  components:{
    'child-box':childBox
  },
  methods:{
    getTabIndex(index){
      this.showIndex=index;
    }
  }
}
</script>

 

三、父組件事件觸發子組件

現在有這么一個需求,在父組件的某一個地方,點擊 可以切換tab,這個需求也得益於公司的一個項目

https://emdatahkush5.eastmoney.com/view/financeCalendar.html#/

如圖,點擊 【全部】選項卡 下的 “查看更多”按鈕切換到 其他的tab 頁。

此時的做法是

1、父組件的button元素綁定click事件,該事件指向  tabToThree  方法

2、在 組件中 給父組件注冊一個 ref="childTab"  。

3、父組件的 childTab  的方法在處理時,使用 $refs.childTab  把事件傳遞給子組件的  handelSwitch  方法,同時攜帶着父組件中的參數 index 

4、子組件接收到父組件的事件后,調用 handelSwitch 方法,把接收到的 index 放到  actIndex中,觸發 tab選項卡的同步變化。

 源碼地址 https://github.com/zuobaiquan/vue/tree/master/vueExercise/vue-component


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM