如何设置prop与泛型数组?



我有一个选择组件,我要做的就是以这种方式实现组件,这样我就可以传递任何类型的数组。如何做到这一点?泛型应该在哪里定义?我使用<script setup>与typescript。

我是这样定义这些道具的:

const props = defineProps<T[]>({
options: {type: Array as PropType<T[]>, required: true }
})

由于你使用的是TypeScript,所以Vue允许你这样做:

const props = defineProps<{
options: T[];
}>();

https://vuejs.org/api/sfc-script-setup.html typescript-only-features

可以这样使用

const props = defineProps<{
options: string[],
}>();

您可以使用像这样的通用prop类型:

<script setup lang="ts" generic="T extends string, U extends Item">
import type { Item } from './types'
defineProps<{
id: T
list: U[]
}>()
</script>

了解更多:https://vuejs.org/api/sfc-script-setup.html#generics

最新更新