// 子组件 Child.vue
<script setup>
const internalState = ref(0)
const resetState = () => {
internalState.value = 0
}
// 显式暴露resetState方法
defineExpose({
resetState
})
</script>
// 父组件 Parent.vue
<template>
<Child ref="childRef" /> //注意这个写法,ref标识定位元素
<button @click="resetChildState">重置子组件状态</button>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const childRef = ref(null)//定义一个响应式空对象
const resetChildState = () => {
// 通过ref访问子组件暴露的方法
childRef.value?.resetState()//这样访问暴露的方法
}
</script>