Vue3+Vuetify3+TypeScript:如何获取VSelect组件Props定义并复用?
问题:如何继承Vuetify 3 VSelect的Props定义到自定义组件
你的自定义组件试图复用VSelect的Props,但写法不符合Vue SFC的类型要求,触发报错:
[plugin:vite:vue] [@vue/compiler-sfc] type argument passed to defineProps() must be a literal type, or a reference to an interface or literal type.
你的原代码:
<template> <v-select v-bind="{ ...$attrs, ...$props }"> <template v-for="(_, name) in $slots" v-slot:[name]="slotData"><slot :name="name" v-bind="slotData"></slot></template> </v-select> </template> <script setup lang="ts"> import { VSelect as test } from 'vuetify/components/VSelect'; defineProps<test>(); </script>
解决方法
方法1:直接使用Vuetify导出的Props类型
Vuetify 3为每个组件都导出了对应Props类型,命名规则为[组件名]Props,直接引用该类型即可:
<template> <v-select v-bind="{ ...$attrs, ...$props }"> <template v-for="(_, name) in $slots" v-slot:[name]="slotData"> <slot :name="name" v-bind="slotData"></slot> </template> </v-select> </template> <script setup lang="ts"> import { VSelect, type VSelectProps } from 'vuetify/components/VSelect'; defineProps<VSelectProps>(); </script>
方法2:扩展Props添加自定义属性
如果需要在VSelect基础上增加自定义Props,可通过接口继承实现:
<template> <v-select v-bind="{ ...$attrs, ...$props }"> <template v-for="(_, name) in $slots" v-slot:[name]="slotData"> <slot :name="name" v-bind="slotData"></slot> </template> </v-select> </template> <script setup lang="ts"> import { type VSelectProps } from 'vuetify/components/VSelect'; // 继承VSelectProps并添加自定义属性 interface CustomSelectProps extends VSelectProps { customLabel?: string; } defineProps<CustomSelectProps>(); </script>
错误原因说明
defineProps()要求传入的类型参数必须是字面量类型、接口或对这两种类型的直接引用。你原代码中传入的test是VSelect组件的实例类型,并非Props类型,不符合TypeScript类型检查规则,因此触发报错。
内容的提问来源于stack exchange,提问作者Pierre-Yves
相关产品推荐
相关产品推荐

