1

组件通信

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>

water_law
43 声望2 粉丝

生活的脚步很沉重,即便如此, 还是要坚持,相信努力才能有所收获。