vue3中defineExpose的用法(和ref配合)

// 子组件 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>

 

posted @ 2025-09-12 16:17  充实地生活着  阅读(53)  评论(0)    收藏  举报