vue3 组件通信 您所在的位置:网站首页 vue3修改父组件的值 vue3 组件通信

vue3 组件通信

2023-11-28 03:33| 来源: 网络整理| 查看: 265

该文章讲的是父子通信,父组件通过 ref 获取子组件的属性,子组件通过 $parent 获取父组件的属性。同时,由于组件内部数据默认是只能组件内部自己访问,所以想让外部访问到必须使用 defineExpose() 方法对外暴露。当然了,获取方法也和获取数据同理。

ref

Parent.vue

我是父组件 {{ count }} 加10 import { ref } from "vue"; import Child1 from "./Child1.vue"; let count = ref(100); // 获取子组件的实例 let child1 = ref() const handler = () => { count.value += 10; // 获取子组件的数据 child1.value.count += 10 };

Child1.vue

我是子组件1 {{ count }} import { ref } from 'vue' let count = ref(10) // 组件内部的数据默认对外是关闭的,只能内部使用,如果想让外部访问,要使用该方法对外暴露 defineExpose({ count }) $parent

Parent.vue

我是父组件 {{ count }} 加10 import { ref } from "vue"; import Child2 from "./Child2.vue"; let count = ref(100); defineExpose({ count })

Child2.vue

我是子组件2 {{ count }} 加 10 import { ref } from 'vue' let count = ref(10) const handler = ($parent) => { count.value += 10 $parent.count += 10 } 总结 ref 获取子组件实例,想要获取子组件的属性和方法,子组件内部使用 defineExpose() 对外暴露即可,使用时调用 ref.value.xxx $parent 获取父组件实例,想要获取父组件的属性和方法,父组件内部使用 defineExpose() 对外暴露即可,使用时调用 $parent.xxx


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有