thi*_*ign 4 vue.js nuxt.js vuejs3 vue-composition-api nuxtjs3
我将 Nuxt 3 / Vue 3defineProps与 TypeScript 结合使用,并希望从 TypeScript 类型推断 types prop 类型。
import { User } from '~/types/types'
const props = defineProps({
users: {
type: Array, // User[]?
},
})
Run Code Online (Sandbox Code Playgroud)
在此示例中,如何使usersprop 成为 的类型User[]?
使用Vue的PropType
import { PropType } from 'vue'
import { User } from '~/types/types'
const props = defineProps = ({
users: {
type: Array as PropType<User[]>
},
})
Run Code Online (Sandbox Code Playgroud)
您还可以使用纯类型语法:
import { User } from '~/types/types'
const props = defineProps<{users:User[], title:string}>()
Run Code Online (Sandbox Code Playgroud)
您可以使用 helper 添加默认值withDefaults:
const props = withDefaults(defineProps<{users:User[], title:string}>(),{
users:()=>[],// in arrays and object use factory function to return the value
title:''
})
Run Code Online (Sandbox Code Playgroud)