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

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

 

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

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

子組件部分:vue

若是須要從父組件獲取  username  的值,就須要java

props:{
   username:{
      type:String
   }
}

示例代碼git

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

在 props 中添加了元素以後,就不須要在 data 中再添加變量啦。github

 父組件部分:數組

示例代碼this

<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>

 

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

通常狀況下,子組件主要經過事件傳遞數據給父組件spa

子組件部分:

示例代碼code

<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>

 

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

如今有這麼一個需求,在父組件的某一個地方,點擊 能夠切換tab,這個需求也得益於公司的一個項目

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

如圖,點擊 【所有】選項卡 下的 「查看更多」按鈕切換到 其餘的tab 頁。

此時的作法是

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

二、在 組件中 給父組件註冊一個 ref="childTab"  。

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

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

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

相關文章
相關標籤/搜索