在 Vue3 中,子组件实例的 Ref 使用规范如下:
1. 基本使用
vue
<!-- 父组件模板 --> <template> <ChildComponent ref="childRef" /> </template> <script setup> import { ref, onMounted } from 'vue' import ChildComponent from './ChildComponent.vue' const childRef = ref(null) // 创建 ref onMounted(() => { if (childRef.value) { childRef.value.someMethod() // 确保子组件已挂载 } }) </script>
2. 子组件暴露属性/方法
子组件需使用 defineExpose
显式暴露内容:
vue
<!-- 子组件 ChildComponent.vue --> <script setup> const someMethod = () => console.log('Method called!') const data = 'Hello' defineExpose({ // 暴露给父组件 someMethod, data }) </script>
3. TypeScript 类型支持
为 Ref 提供准确的类型:
typescript
import ChildComponent from './ChildComponent.vue' const childRef = ref<InstanceType<typeof ChildComponent> | null>(null)
4. 注意事项
-
挂载时机:在
onMounted
或之后访问 Ref,确保子组件已渲染。 -
v-for 中的 Ref:Ref 会存储为数组,需处理数组逻辑:
vue
<template> <ChildComponent v-for="item in list" :ref="addRef" /> </template> <script setup> const refs = ref([]) const addRef = (el) => { refs.value.push(el) } </script>
5. Options API 兼容
在 Options API 中使用 this.$refs
:
vue
<script> export default { mounted() { this.$refs.childRef.someMethod() } } </script>
总结步骤
-
父组件:使用
ref
创建引用并绑定到子组件。 -
子组件:通过
defineExpose
暴露必要内容。 -
类型安全:用
InstanceType<typeof Component>
定义类型。 -
访问时机:在
onMounted
后操作 Ref,避免null
错误。
常见问题排查:
-
检查子组件是否使用
defineExpose
。 -
确保 Ref 类型正确定义。
-
避免在挂载前访问 Ref 内容。