Vue.js 基礎 - 組件通訊

組件通訊

1. 父組件向子組件單向通訊

父組件經過子組件的 prop 屬性單向地向子組件通訊

// 父組件
<template>
  <div id="school">
    <!--僅 0 '' false 以及 null undefined 被識別爲 false -->
    <div v-if="schools.length">
      <div class="school_list" v-for="(school, index) in schools">
        <school :item="school"></school>
      </div>
    </div>
  </div>
</template>
<script>
  import School from '@/components/School'
  export default {
    name: 'schools',
    data () {
      return {
        schools: [
          { name: '華僑大學', major: 'Architecture' },
          { name: '集美大學', major: 'Accounting' },
          { name: '廈門大學', major: 'Economics' }
        ]
      }
    },
    components: { School }
  }

</script>
// 子組件
<template>
  <div class="school_info">
    <li>{{ item.index }}.{{ item.name }}</li>
    <li>{{ item.major }}</li>
  </div>
</template>
<script>
  export default {
    name: 'school',
    props: ['item']
  }
</script>
<style scoped>
  li {
    list-style-type: none;
    margin: 10px;
  }
</style>

2. 子組件 emit 一個事件向父組件通訊

// 子組件
<template>
  <div id="custom">
     <div class="childToFather">
       <button @click="add">{{ count }}</button>
     </div>
  </div>
</template>
<script>
export default {
  name: 'childComponent',
  data () {
    return {
      count: 0
    }
  },
  methods: {
    add () {
      // typeof operator is one of the following string literals:
      // "undefined", "object", "boolean", "number", "string", "function" and "symbol"
      // 子組件經過 $emit觸發父組件的方法
      this.$emit('add')
      // this.emit(eventName, param1, param2, param3...) 能夠將數據回調到 on 端
    }
  }
}
</script>
// 父組件
<template>
  <div>
    <div id="childToFather">
      <child-component @add="count"></child-component>  // 事件冒泡到父組件
    </div>
  </div>
</template>

<script>
  import ChildComponent from '@/components/ChildComponent'
  export default {
    name: 'father',
    components: { ChildComponent },
    methods: {
    // 對應子組件 emit 的參數個數
      count ((param1, param2, param3...) => {
        // do something
      }) {
      }
    }
  }

</script>
相關文章
相關標籤/搜索