// 子組件 Child.vue
<script setup>
const internalState = ref(0)
const resetState = () => {
internalState.value = 0
}
// 顯式暴露resetState方法
defineExpose({
resetState
})
</script>
// 父組件 Parent.vue
<template>
<Child ref="childRef" /> //注意這個(gè)寫法,ref標(biāo)識(shí)定位元素
<button @click="resetChildState">重置子組件狀態(tài)</button>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const childRef = ref(null)//定義一個(gè)響應(yīng)式空對(duì)象
const resetChildState = () => {
// 通過(guò)ref訪問(wèn)子組件暴露的方法
childRef.value?.resetState()//這樣訪問(wèn)暴露的方法
}
</script>