vue3父组件 调用子组件 方法
父组件:通过ref获取子组件实例
<template>
<div style="text-align:center">
<button @click="callChildMethod">点击获取子组件数据</button>
<div>
获取到子组件的数据如下:
<div> {{childData}} </div>
</div>
<ChildComponent ref="ChildComponentRef"/>
</div>
</template>
<script setup>
import { ref } from "vue";
import ChildComponent from "@/components/childComponent.vue";
const ChildComponentRef = ref(null); // 获取子组件实例(需要跟ref处同名)
let childData = ref();
const callChildMethod = () =>{
if (ChildComponentRef.value) {
childData.value = ChildComponentRef.value.userName +'在'+ ChildComponentRef.value.doSomething()
}
}
</script>
defineExpose 的引入是为了提供一种清晰的方式来控制组件的公共接口,避免所有的内部状态都被外部访问,从而增强组件的封装性。
如果你想让外部组件访问到 <script setup> 内定义的属性或方法,你需要使用 defineExpose 显式地暴露它们。
<template>
<!-- <p>子组件</p> -->
</template>
<script setup>
import { ref, defineExpose } from "vue";
const userName = ref("张三");// 属性
const doSomething () => ({
return "写代码"
});
// 暴露方法
defineExpose({
doSomething,// 暴露方法
userName,// 暴露属性
});
</script>
本文作者:独而不孤
本文链接:https://www.cnblogs.com/lcaiqin/p/18283962
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步