props参数验证
不符合设定参数形式,会报警告但不会终止程序
type类型:
String、Number、Boolean、Array、Object、Date、Function、Symbol
0、自定义构造函数:内部通过 instanceof 来进行检查确认
如:
function Person (firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
你可以使用:
Vue.component('blog-post', {
props: {
author: Person 验证author的值是否是通过new Person创建的。
}
})
1、验证参数类型
将原本的props:[xx]替换成
props:{
参数名:首字母大写的类型,
参数名:[类型1,类型2,...] 多个可能的类型
}
2、设置参数默认值(即不传参数也能显示)
props:{
参数:{
type:参数类型,
default:默认值(只能设置基本数据类型)
}
}
设置复杂类型参数默认值(如数组等)
props:{
参数:{
type:参数类型,
default:function()
{
return xx
}
}
}
3、设置必传参数
props:{
参数:{
type:参数类型,
required:true
}
}
4、设置自定义验证规则,返回布尔值
props:{
参数:{
validator:function(v){
return 判断后的布尔值
}
}
}
如:
propF: {
validator: function (value) {
这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
代码示例:
子组件:
<template>
<div>
子组件
{{msg}}
{{age}}
{{name}}
{{nick}}
{{address}}
{{sex}}
<ul>
<li v-for='num in sex'>{{num}}</li>
</ul>
<button @click='send'>传给父组件</button>
</div>
</template>
<script>
export default{
name:'B',
data()
{
return{
}
},
props:{
msg:String,
age:Number,
name:String,
nick:{
type:String,
default:'nick2'
},
address:{
type:String,
required:true
},
sex:{
type:Array,
default:function(){
return [1,2,3]
}
}
},
methods:{
send()
{
this.$emit('info','来自子组件');
}
}
}
</script>
<style lang='css'>
<style>
父组件:
<template>
<div>
父组件
<B msg='aaaa' @info='receive' name='jeff' :age=18 />
{{msg}}
</div>
</template>
<script>
import B from './B'
export default{
name:'A',
data()
{
return{
msg:''
}
},
methods:{
receive(data)
{
this.msg=data
}
},
components:{
B
}
}
</script>
<style lang='css'>
<style>