<a-select:ref="(el) => (listItem.attributeTypeRef = el)"v-model:value="modelData[listIndex].bindAttributeTypeSelected"option-label-prop="label":disabled="listItem.attributeTypeDisabled":loading="listItem.attributeTypeLoading":placeholder="$t('message.selection')"@select="selectAttributeType(listIndex)"@change="changeAttributeType"@focus="setRowIndex(listIndex)"style="width: 150px">
TS类型标注
为 dom 模板引用标注类型
模板 ref 需要通过一个显式指定的泛型参数和一个初始值 null 来创建
<script setup lang="ts">import { ref, onMounted } from 'vue'const el = ref<HTMLInputElement | null>(null)onMounted(() => {el.value?.focus()})</script><template><input ref="el" /></template>
注意为了严格的类型安全,有必要在访问 el.value 时使用可选链或类型守卫。这是因为直到组件被挂载前,这个 ref 的值都是初始的 null,并且 v-if 将引用的元素卸载时也会被设置为 null。
InstanceType 为组件模板引用定义 TS 类型
首先需要通过 typeof 得到组件类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型
const Foo = defineComponent(/* ... */)type FooInstance = InstanceType<typeof Foo>
setup() {const modal = ref<InstanceType<typeof MyModal>>()const openModal = () => {modal.value?.open()}return { modal, openModal }}
请注意你还需要使用可选链操作符或其它方式来确认 modal.value 不是 undefined。
