今天在开发中,突然想到,平时定义组件的props时,在引入了ts后,常用于定义他的类型或者默认值,看了一下官方文档,对组件props的定义提供了几种方法。
一、官网地址:Vue.js - 渐进式 JavaScript 框架 | Vue.js
二、
用法1:只定义默认值,直接使用defineProps就可以
const props = defineProps({
options: {
type: Array,
default: () => [{ label: '男', value: 1 }]
}
})
用法2:针对类型的 props声明,props 可以通过给 defineProps
传递纯类型参数的方式来声明。具体写法如下:
// 2.defineProps<泛型参数>()的方式 没办法做默认赋值
type propsType = {
options: {
label: string
value: string | number
}[]
}
const props = defineProps<propsType>()
用法3: 使用类型声明时的默认 props 值,vue官方为我们提供了withDefaults
编译器宏。具体写法如下:
// 3.withDefaults 编译器宏 泛型加默认值
type propsType = {
options: {
label: string
value: string | number
}[]
}
const props = withDefaults(defineProps<propsType>(), {
options: () => [
{
label: '男',
value: 1
}
]
})