在 Vue3 中使用 TypeScript 时,通过 ref
获取标签(包括 DOM 元素或组件实例)的 TypeScript 类型定义需根据场景区分:
1. 获取 DOM 元素的类型
若 ref
绑定的是原生 DOM 元素(如 <div>
、<input>
),需使用 HTML 元素的内置类型:
import { ref } from 'vue';
// 示例:获取 div 元素
const divRef = ref<HTMLDivElement | null>(null);
// 示例:获取 input 元素
const inputRef = ref<HTMLInputElement | null>(null);
- 原因:DOM 元素类型由浏览器环境定义,如
HTMLDivElement
、HTMLInputElement
等。 - 注意:初始值需设为
null
,因为元素在组件挂载前不存在 。
2. 获取子组件的类型
若 ref
绑定的是 Vue 组件(自定义组件或第三方组件),需使用 InstanceType<typeof 组件>
工具类型:
import { ref } from 'vue';
import MyComponent from '@/components/MyComponent.vue';
// 获取自定义组件的实例类型
const myCompRef = ref<InstanceType<typeof MyComponent> | null>(null);
第三方组件库示例(如 Element Plus)
import { ref } from 'vue';
import { ElTree } from 'element-plus';
// 定义组件实例类型
type TreeType = InstanceType<typeof ElTree>;
const treeRef = ref<TreeType | null>(null);
- 关键点:
typeof 组件
获取组件的构造函数类型。InstanceType
提取该构造函数的实例类型(即组件暴露的方法/属性)。- 联合
null
处理初始状态 。
3. 动态生成标签的 ref 类型
若通过函数动态绑定 ref
(如 :ref="getRef"
),需在函数内手动指定类型:
<template>
<el-input :ref="getInputRef" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import type { ElInput } from 'element-plus';
type InputType = InstanceType<typeof ElInput>;
const inputRef = ref<InputType | null>(null);
const getInputRef = (el: unknown) => {
inputRef.value = el as InputType; // 显式类型断言
};
</script>
- 原因:动态
ref
的回调参数el
类型为unknown
,需手动转换为目标类型
本文固定连接:https://code.zuifengyun.com/2025/07/3613.html,转载须征得作者授权。