Vue 组件可以更细致地声明对传入的 props 的校验要求。比如我们上面已经看到过的类型声明,如果传入的值不满足类型要求,Vue 会在浏览器控制台中抛出警告来提醒使用者。这在开发给其他开发者使用的组件时非常有用。
要声明对 props 的校验,你可以向 defineProps() 宏提供一个带有 props 校验选项的对象,例如:
defineProps({// 基础类型检查// (给出 `null` 和 `undefined` 值则会跳过任何类型检查)propA: Number,// 多种可能的类型propB: [String, Number],// 必传,且为 String 类型propC: {type: String,required: true},// Number 类型的默认值propD: {type: Number,default: 100},// 对象类型的默认值propE: {type: Object,// 对象或数组的默认值// 必须从一个工厂函数返回。// 该函数接收组件所接收到的原始 prop 作为参数。default(rawProps) {return { message: 'hello' }}},// 自定义类型校验函数// 在 3.4+ 中完整的 props 作为第二个参数传入propF: {validator(value, props) {// The value must match one of these stringsreturn ['success', 'warning', 'danger'].includes(value)}},// 函数类型的默认值propG: {type: Function,// 不像对象或数组的默认,这不是一个// 工厂函数。这会是一个用来作为默认值的函数default() {return 'Default function'}}
}) 
一些补充细节:
-  
所有 prop 默认都是可选的,除非声明了
required: true。 -  
除
Boolean外的未传递的可选 prop 将会有一个默认值undefined。 -  
Boolean类型的未传递 prop 将被转换为false。这可以通过为它设置default来更改——例如:设置为default: undefined将与非布尔类型的 prop 的行为保持一致。 -  
如果声明了
default值,那么在 prop 的值被解析为undefined时,无论 prop 是未被传递还是显式指明的undefined,都会改为default值。 
当 prop 的校验失败后,Vue 会抛出一个控制台警告 (在开发模式下)。
如果使用了基于类型的 prop 声明 ,Vue 会尽最大努力在运行时按照 prop 的类型标注进行编译。举例来说,defineProps<{ msg: string }> 会被编译为 { msg: { type: String, required: true }}。
运行时类型检查
校验选项中的 type 可以是下列这些原生构造函数:
StringNumberBooleanArrayObjectDateFunctionSymbolError
另外,type 也可以是自定义的类或构造函数,Vue 将会通过 instanceof 来检查类型是否匹配。例如下面这个类:
class Person {constructor(firstName, lastName) {this.firstName = firstNamethis.lastName = lastName}
} 
可以将其作为一个 prop 的类型: 
defineProps({author: Person
}) 
Vue 会通过 instanceof Person 来校验 author prop 的值是否是 Person 类的一个实例。