vue3组合式API实现父组件触发子组件中的方法 | vue3中ref的用法 | defineExpose的使用场景
一、问题背景
代码环境:vue3 (组合式API setup)+ vite
碰到的问题:代码为父组件中的一个按钮,触发一个填写表单的Dialog弹出框,在填写信息发送请求添加一条信息后,再次点击触发按钮,发现封装Dialog的子组件中,表单中的值没有没有重置。
解决思路:在点击父组件中的触发按钮时,触发子组件中的重置方法,对表单项进行重置。
二、解决方法
在 Vue 3 的组合式 API 中,您可以使用 ref 和 value 来获取子组件实例,并调用子组件中的方法。
官网详解:
网址:组件上的ref
三、示例
- 在父组件中,您需要为子组件添加一个 ref:
<template>
<div>
<child-component ref="childRef"></child-component>
<button @click="triggerChildMethod">触发子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const childRef = ref(null);
const triggerChildMethod = () => {
childRef.value.methodName(/* 参数 */);
};
return {
childRef,
triggerChildMethod
};
}
}
</script>
- 在子组件中,您需要在 setup 函数中定义一个需要调用的方法:
<template>
<div>
<!-- 子组件内容 -->
</div>
</template>
<script setup>
import { ref } from 'vue';
const methodName = () => {
// 方法的代码
};
// !!!!!用了<script setup>的不要忘记写这个
defineExpose({
methodName
});
</script>
注:使用了 <script setup>
的组件是默认私有的:一个父组件无法访问到一个使用了 <script setup>
的子组件中的任何东西,除非子组件在其中通过 defineExpose
宏显式暴露。如果没有暴露的话,则会报错childRef.value.methodName is not definded
。
该注释的官网详解:(地址:组件上的ref,该网页滑到最后可看到下图内容)