如何动态获取Vue3组件Prop的TS类型以实现Ref自动补全?
实现Vue3组件Prop类型的动态绑定
方法一:使用Vue内置的ComponentProps工具类型(无需修改子组件)
直接利用Vue提供的ComponentProps类型提取目标组件的Props类型,再通过索引访问获取指定Prop的类型:
父组件ParentComponent.vue代码:
<template> <ChildComponent :text="myText" /> </template> <script setup lang="ts"> import ChildComponent from './ChildComponent'; import type { ComponentProps } from 'vue'; // 获取ChildComponent的所有Props类型 type ChildProps = ComponentProps<typeof ChildComponent>; // 提取text Prop的类型 type TextProp = ChildProps['text']; // 此时TextProp会被推导为string,myText获得对应的类型提示和自动补全 const myText = ref<TextProp>("hello"); </script>
方法二:子组件手动导出Props类型(更灵活)
如果需要更明确的类型导出,可以修改子组件,将Props类型对外暴露:
子组件ChildComponent.vue修改后:
<script setup lang="ts"> const props = defineProps<{ text: string; }>(); // 导出Props类型供外部使用 export type ChildProps = typeof props; </script>
父组件ParentComponent.vue代码:
<template> <ChildComponent :text="myText" /> </template> <script setup lang="ts"> import ChildComponent, { type ChildProps } from './ChildComponent'; // 提取text Prop的类型 type TextProp = ChildProps['text']; const myText = ref<TextProp>("hello"); </script>
说明
两种方法都能让myText的类型与子组件的text Prop严格绑定,获得TypeScript的自动补全和类型校验。如果不想改动子组件,优先选择方法一;如果需要对子组件的类型做更自定义的导出,方法二更合适。
内容的提问来源于stack exchange,提问作者Felix Eklöf
相关产品推荐
相关产品推荐

