如何在 Vue 3 的 <script setup> 中输入通用组件?

Mys*_*ood 22 typescript typescript-generics vuejs3 vue-composition-api

我有一个 Select 组件,它接受options. 每个都option可以是任何事物的对象,只要它具有以下属性id并且text

所以我这样输入:

type SelectOption<T> = {
  id: string | number
  text: string
} & T
Run Code Online (Sandbox Code Playgroud)

但我不确定如何在组件中使用definePropsdefineEmits

defineProps<{
  options: SelectOption<??>
  modelValue: SelectOption<??>
}>()

defineEmits<{
  (event: 'update:modelValue', SelectOption<??>): void
}>()
Run Code Online (Sandbox Code Playgroud)

小智 21

这是一个更新的答案,以说明该领域的最新改进:

这允许您编写以下代码(来自链接的发布博客文章):

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

当然,这需要你升级到最新版本的 vue 和 volar。

请注意,截至撰写本文时(2023 年 5 月),此功能的边缘有点粗糙,但仍在积极开发中。