Vue组件高级通讯之$children与$parent

 更新时间:2023年06月25日 14:59:06   作者:扶得一人醉如苏沐晨  
这篇文章主要为大家介绍了Vue组件高级通讯之$children与$parent,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

一、$children组件属性

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

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

二、$parent

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

如果组件没有父组件,他的$parent为undefined,App组件(根组件)的$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组件高级通讯之$children与$parent的详细内容,更多关于Vue组件通讯$children $parent的资料请关注脚本之家其它相关文章!

相关文章

最新评论