如何在Nuxt 3/Vue 3中通过defineProps定义User[]类型的props?
在Nuxt 3/Vue 3中给defineProps定义User[]类型的两种方法
方法1:纯类型声明(推荐,简洁直观)
直接用TypeScript类型定义props,Vue会自动完成类型推断,无需额外运行时类型标注:
import { User } from '~/types/types' // <>内传入类型定义,?表示该属性可选,去掉则为必填项 const props = defineProps<{ users?: User[] }>()
方法2:运行时选项结合类型标注(需运行时验证时使用)
如果需要添加默认值、必填校验这类运行时逻辑,可以引入PropType来指定数组的元素类型:
import { defineProps, PropType } from 'vue' import { User } from '~/types/types' const props = defineProps({ users: { type: Array as PropType<User[]>, // 用PropType<User[]>标注数组元素的具体类型 required: false, // 可选:设置属性是否必填 default: () => [] // 可选:设置默认值为空白数组 } })
内容的提问来源于stack exchange,提问作者thisismydesign
相关产品推荐
相关产品推荐

