1. 程式人生 > 其它 >vue 元件間 8 大通訊方式 之一 props / $emit $children / $parent

vue 元件間 8 大通訊方式 之一 props / $emit $children / $parent

一、props/$emit (最常用)

1.父傳子 props

// section父元件
<template>
  <div class="section">
    <com-article :articles="articleList"></com-article>
  </div>
</template>

<script>
import comArticle from './test/article.vue'
export default {
  name: 'HelloWorld',
  components: { comArticle },
  data() {
    
return { articleList: ['紅樓夢', '西遊記', '三國演義'] } } } </script>
// 子元件 article.vue
<template>
  <div>
    <span v-for="(item, index) in articles" :key="index">{{item}}</span>
  </div>
</template>

<script>
export default {
  props: ['articles']
}
</script>

注意:prop 只可以從上一級元件傳遞到下一級元件(父子元件),即所謂的單向資料流。而且 prop 只讀,不可被修改,所有修改都會失效並警告。

2.子傳父 $emit

對於$emit我自己的理解是這樣的:$emit繫結一個自定義事件, 當這個語句被執行時, 就會將引數arg傳遞給父元件,父元件通過v-on監聽並接收引數。

// 父元件中
<template>
  <div class="section">
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
    <p>{{currentIndex}}</p>
  </div>
</template>

<script>
import comArticle from 
'./test/article.vue' export default { name: 'HelloWorld', components: { comArticle }, data() { return { currentIndex: -1, articleList: ['紅樓夢', '西遊記', '三國演義'] } }, methods: { onEmitIndex(idx) { this.currentIndex = idx } } } </script>
//子元件
<template> <div> <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div> </div> </template> <script> export default { props: ['articles'], methods: { emitIndex(index) { this.$emit('onEmitIndex', index) } } } </script>

二、$children/$parent

在父子元件中,可以通過this.$parent 或者 this.$children 訪問父子例項,拿到例項代表什麼?代表可以訪問此元件的所有方法和data。 但是官方說盡量節省使用此方法,推薦通過props 和 $emit 去實現通訊

// 父元件中
<template>
  <div class="hello_world">
    <div>{{msg}}</div>
    <com-a></com-a>
    <button @click="changeA">點選改變子元件值</button>
  </div>
</template>

<script>
import ComA from './test/comA.vue'
export default {
  name: 'HelloWorld',
  components: { ComA },
  data() {
    return {
      msg: 'Welcome'
    }
  },

  methods: {
    changeA() {
      // 獲取到子元件A
      this.$children[0].messageA = 'this is new value'
    }
  }
}
</script>
// 子元件中
<template>
  <div class="com_a">
    <span>{{messageA}}</span>
    <p>獲取父元件的值為:  {{parentVal}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messageA: 'this is old'
    }
  },
  computed:{
    parentVal(){
      return this.$parent.msg;
    }
  }
}
</script>

注意邊界情況,如在#app上拿$parent得到的是new Vue()的例項,在這例項上再拿$parent得到的是undefined,而在最底層的子元件拿$children是個空陣列。也要注意得到$parent$children的值不一樣,$children的值是陣列,而$parent是個物件

小結

上面兩種方式用於父子元件之間的通訊, 而使用props進行父子元件通訊更加普遍; 二者皆不能用於非父子元件之間的通訊。