Vue3父组件读取子组件属性方法(通过模板引用)
在子组件中暴露属性:子组件必须使用 defineExpose 编译器宏,显式暴露需要被父组件访问的属性和方法。
// ChildComponent.vue
<script setup>
import { ref } from 'vue'
const childCount = ref(0)
const childMethod = () => {
childCount.value++
console.log('子组件方法被调用')
}
// 关键步骤:暴露给父组件
defineExpose({
childCount,
childMethod
})
</script>