20250317-vue-Prop4
运行时类型检查
校验选项中的 type 可以是下列这些原生构造函数:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
- Error
另外,type 也可以是自定义的类或构造函数,Vue 将会通过 instanceof 来检查类型是否匹配。例如下面这个类:
class Person {
constructor(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
我们可以将其作为一个 prop 的类型:
<template>
<text>{{aProp.message}}</text>
</template>
<script>
import Person from './Person.js'
export default {
props:{
author:Person
}
}
</script>
<style>
</style>
Vue 会通过 instanceof Person 来校验 author prop 的值是否是 Person 类的一个实例。
js文件:
const Person = {
class Person {
constructor(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
}
export default Person
子组件代码:
<template>
<text>{{aProp.message}}</text>
</template>
<script>
import Person from './Person.js'
export default {
props:{
author:Person
}
}
</script>
<style>
</style>
父组件代码:
<template>
<Sub :author="anObject"></Sub>
</template>
<script>
import Sub from './Sub.vue'
export default {
components: {
Sub,
},
data() {
return {
anObject:{
anProperty:'anProperty'
}
}
}
}
</script>
<style>
</style>
报错:
Invalid prop: type check failed for prop "author". Expected Person, got Object
可为 null 的类型
如果该类型是必传但可为 null 的,你可以用一个包含 null 的数组语法:
export default {
props:{
id:{
type:[string,null],
required:true
}
}
}
注意如果 type 仅为 null 而非使用数组语法,它将允许任何类型。
Boolean 类型转换
声明为 Boolean 类型的 props 有特别的类型转换规则。以带有如下声明的 <MyComponent> 组件为例:
export default {
props: {
disabled: Boolean
}
}
该组件可以被这样使用:
<!-- 等同于传入 :disabled="true" -->
<MyComponent disabled />
<!-- 等同于传入 :disabled="false" -->
<MyComponent />
当一个 prop 被声明为允许多种类型时,Boolean
的转换规则也将被应用。然而,当同时允许 String
和 Boolean
时,有一种边缘情况——只有当 Boolean
出现在 String
之前时,Boolean
转换规则才适用:
// disabled 将被转换为 true
export default {
props: {
disabled: [Boolean, Number]
}
}
// disabled 将被转换为 true
export default {
props: {
disabled: [Boolean, String]
}
}
// disabled 将被转换为 true
export default {
props: {
disabled: [Number, Boolean]
}
}
// disabled 将被解析为空字符串 (disabled="")
export default {
props: {
disabled: [String, Boolean]
}
}