20250314-vue-Props3
Props 校验
vue组件可以更细致地声明对传入的 props 的校验要求。比如类型声明,如果传入的值不满足类型要求,Vue会在浏览器控制台中抛出警告来提醒使用者。这在开发给其他开发者使用的组件时非常有用。
要声明对 props 的校验,可以向 props 选项提供一个带有 props 校验选项的对象,例如:
1 基础类型检查
子组件:
<template>
<text>{{aProp}}</text>
</template>
<script>
export default {
props:{
//基础类型检查
//(给出 'null' 和 'undefined' 值则会跳过任何类型检查)
aProp:Number
}
}
</script>
<style>
</style>
父组件:
<template>
<Sub aProp="3"></Sub>
</template>
<script>
import Sub from './Sub.vue'
export default {
components: {
Sub,
},
data() {
return {
}
}
}
</script>
<style>
</style>
结果:
报错 [Vue warn]: Invalid prop: type check failed for prop "aProp". Expected Number with value 3, got String with value "3".
显示还是会显示
2 多种可能的类型
上面的例子,把子组件代码改成这样,就不会收到警告了,
<template>
<text>{{aProp}}</text>
</template>
<script>
export default {
props:{
//多种可能类型
aProp:[Number,String]
}
}
</script>
<style>
</style>
3 必传,且为 String 类型
子组件改成这样,
<template>
<text>{{aProp}}</text>
</template>
<script>
export default {
props:{
//必传,且为 String 类型
aProp:{
type:String,
required:true
}
}
}
</script>
<style>
</style>
父组件不传,报错 Missing required prop: "aProp"
父组件传数字类型,也会报错,Invalid prop: type check failed for prop "aProp". Expected String with value "3", got Number with value 3.
注意带冒号才算传的数值类型3,不带冒号则表示传的是字符串3
<template>
<Sub :aProp="3"></Sub>
</template>
<script>
import Sub from './Sub.vue'
export default {
components: {
Sub,
},
data() {
return {
}
}
}
</script>
<style>
</style>
4 必传但可为 null 的字符串
上面3中如果传null,是会报错的,改成这样就不会,
<template>
<text>{{aProp}}</text>
</template>
<script>
export default {
props:{
//必传但可为null的字符串
aProp:{
type:[String,null],
required:true
}
}
}
</script>
<style>
</style>
父组件:
<template>
<Sub :aProp="null"></Sub>
</template>
<script>
import Sub from './Sub.vue'
export default {
components: {
Sub,
},
data() {
return {
}
}
}
</script>
<style>
</style>
5 Number 类型的默认值
<template>
<text>{{aProp}}</text>
</template>
<script>
export default {
props:{
//必传但可为null的字符串
aProp:{
type:Number,
default:101
}
}
}
</script>
<style>
</style>
6 对象类型的默认值
子组件:
<template>
<text>{{aProp.message}}</text>
</template>
<script>
export default {
props:{
//对象类型的默认值
aProp:{
type: Object,
// 对象或者数组应当用工厂函数返回
// 工厂函数会收到组件所接收的原始 props 作为参数
default(rawProps) {
return {message:'子类默认'}
}
}
}
}
</script>
<style>
</style>
父组件:
<template>
<Sub :a-prop="{message:'父组件传入'}"></Sub>
</template>
<script>
import Sub from './Sub.vue'
export default {
components: {
Sub,
},
data() {
return {
}
}
}
</script>
<style>
</style>
如果父组件不传该属性,则显示:
7 自定义类型校验函数(不常用)
// 自定义类型校验函数
// 完整的 props 作为第二个参数传入
propG: {
validator(value, props) {
return ['success', 'warning', 'danger'].includes(value)
}
},
一些补充细节:
-
所有 prop 默认都是可选的,除非声明了 required: true
-
除 Boolean 外的未传递的可选 prop 将会有一个默认值 undefined
-
Boolean 类型的未传递 prop 将被转换为 false。这可以通过为它设置 default 来更改——例如,设置为 default:undefined 将与非布尔类型的 prop 的行为保持一致
-
如果声明了 default 值,那么在 prop 的值被解析为 undefined 时,无论 prop 是未被传递还是显式指明的 undefined,都会改为 default 值
需要注意的是,prop 的校验是在组件实例被创建之前,所以实例的属性比如 data、computed 等将在 default 或 validator 函数中不可用。