Vue父子組件通信:$parent、$children

1,492 阅读1分钟

父组件

<!-- 父组件 -->
<template>
  <div>
    <h1>父组件</h1>
    <h3>{{msg}}</h3>
    <button @click="doChildren">调用子组件的数据和方法</button>
    <child v-for="(item,i) in list" :key="i" :number="item"></child>
  </div>
</template> 

<script>
import Child from "./Children";

export default {
  components: { Child },
  data() {
    return {
      msg: "parent message",
      list: [1,2,3]
    };
  },
  mounted() {
    console.log("父组件打印子组件实例:", this.$children);
    for (let v of this.$children) {
      console.log("子组件信息", v.cMD);
    }
  },
  methods: {
    doParent() {
      console.log("parent doParent()");
      this.msg = "change parent message";
    },
    doChildren() {
      console.log(this.$children);
      this.$children[0].doChildren()
    }
  },
};
</script>
<style scoped>
</style>

子组件

<!-- 子组件1 -->
<template>
  <div class="child">
    <h2>我是子组件{{number}}</h2>
    <h3>{{cMD}}</h3>
    <h4>{{msg}}</h4>
    <button @click="doParent">调用父组件的数据和方法</button>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      msg: 'child'
    };
  },
  props: {
    number: {
      type: Number,
      default: 0,
      required: true,
    }
  },
  computed:{
    cMD: function () {
      return 'child'+ this.number
    }
  },
  mounted() {
    // 打印父组件实例
    console.log("mounted:", this.$parent);
    // 打印父组件中属性
    console.log("mounted:", this.$parent.msg);
  },
  methods: {
    doParent() {
      // 打印父组件实例
      console.log(this.$parent);
      // 打印父组件中属性
      console.log(this.$parent.msg);
      // 调用父组件的方法
      this.$parent.doParent();
    },
    doChildren(){
      console.log("children doParent()");
      this.msg = "change children message";
    }
  },
};
</script>
<style scoped>
</style>

子传父

  • 子组件获取父组件实例,打印当前父组件 1620577176(1).png
  • 在子组件的生命周期中均可拿到父组件的值
  • 可以通过调用父组件中的方法,或者直接改变父组件中的属性值

父传子

  • 父组件获取子组件实例,打印当前子组件 1620577609(1).png
  • beforeMount之前都拿不到数据,是由于此时子组件还没有初始化
  • Vue的父组件和子组件 加载渲染过程: 父beforeCreate->父created->父beforeMount->子beforeCreate->子created-> 子 beforeMount->子mounted->父mounted
  • 可以通过调用子组件中的方法,或者直接改变子组件中的属性值
  • $children 并不保证顺序,也不是响应式的。如果你发现自己正在尝试使用 $children 来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。