如何使用通用类型数组设置Prop?

发布于 2025-01-31 10:02:09 字数 261 浏览 0 评论 0原文

我有一个选择的组件,我要做的是以这种方式实现组件,以便我可以通过任何类型的数组。怎么办?通用应在哪里定义?我使用< script设置>和typecript。

这就是我尝试定义道具的方式:

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

I have a select component and what I am trying to do is to implement the component in that way so I can pass an array of any type. How can this be done? Where should the generic be defined? I am using <script setup> with typescript.

This is how I tried to define the props:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枕头说它不想醒 2025-02-07 10:02:09

由于您正在使用Typescript,因此VUE允许您这样做:

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

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

Since you're using TypeScript, Vue allows you to do this:

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

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

柒七 2025-02-07 10:02:09

你可以这样使用

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

you can use like this

const props = defineProps<{
  options: string[],
}>();
岁吢 2025-02-07 10:02:09

您可以使用类似的通用道具类型:

<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-stup.html#generics

You can use generic prop types like so:

<script setup lang="ts" generic="T extends string, U extends Item">
import type { Item } from './types'

defineProps<{
  id: T
  list: U[]
}>()
</script>

Learn more: https://vuejs.org/api/sfc-script-setup.html#generics

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文