美文网首页
Vue组件高级通讯--篇6--$children与$parent

Vue组件高级通讯--篇6--$children与$parent

作者: 扶得一人醉如苏沐晨 | 来源:发表于2023-05-03 08:52 被阅读0次

一、$children组件属性

官方介绍:当前实例的直接子组件。需要注意 $children 并不保证顺序,也不是响应式的。

即$children是组件自带的属性,它可以获取到当前组件的子组件,并以数组的形式返回。

二、$parent

官方介绍:指定已创建的实例之父实例,在两者之间建立父子关系。子实例可以用 this.$parent 访问父实例子实例被推入父实例的 $children 数组中

如果组件没有父组件,他的$parent为undefinedApp组件(根组件)的$parent不是undefined,也不是App本身。

如果组件有多个父亲,但是$parent只能找到一个,不知道是不是bug,建议慎用。

注意:节制地使用$parent 和 $children它们的主要目的是作为访问组件的应急方法。更推荐用 props 和 events 实现父子组件通信。

三、小例子:通过借钱案例加深理解

Father.vue

<template>
  <div>
    <h2>父亲金钱:{{ fatherMoney }}</h2>
    <button @click="jieqian">问子女借钱100元</button>
    <Son></Son>
    <Daughter></Daughter>
  </div>
</template>

<script>
import Son from "./Son";
import Daughter from "./Daughter";
export default {
  components: {
    Son,
    Daughter,
  },
  data() {
    return {
      fatherMoney: 0,
    };
  },
  methods: {
    jieqian() {
      this.fatherMoney += 100 * 2;
      this.$children.forEach((dom) => {
        dom.childrenMoney -= 100;
      });
    },
  },
};
</script>

<style></style>

Son

<template>
  <div style="background-color: #999">
    <h2>儿子金钱:{{ childrenMoney }}</h2>
    <button @click="giveFatherMoney(100)">给父亲100</button>
  </div>
</template>
 
<script>
export default {
  name: "Son",
  data() {
    return {
      childrenMoney : 20000,
    };
  },
  methods: {
    giveFatherMoney(money) {
      this.$parent.fatherMoney += money;
      this.childrenMoney -= money;
    },
  },
};
</script>
 
<style>
</style>

Daughter

<template>
  <div style="background-color: #999">
    <h2>女儿金钱:{{ childrenMoney }}</h2>
    <button @click="giveFatherMoney(100)">给父亲100</button>
  </div>
</template>
 
<script>
export default {
  name: "Daughter",
  data() {
    return {
      childrenMoney : 20000,
    };
  },
  methods: {
    giveFatherMoney(money) {
      this.$parent.fatherMoney += money;
      this.childrenMoney -= money;
    },
  },
};
</script>
 
<style>
</style>

相关文章

网友评论

      本文标题:Vue组件高级通讯--篇6--$children与$parent

      本文链接:https://www.haomeiwen.com/subject/iwbbjdtx.html