普通父子组件传值
const app = Vue.createApp({
data(){
return{
message:'hello world',
num:110
}
},
template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
props:['num'],
template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')
带校验传值
const app = Vue.createApp({
data(){
return{
message:'hello world',
num:110
}
},
template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
props:{
num:String
},
template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')
此时传值为string类型,但是父组件定义的num是数字类型,因此控制台就会提示:
[Vue warn]: Invalid prop: type check failed for prop “num”. Expected String with value “110”, got Number with value 110.
当把 num:110 改为字符串 num:“110” 验证成功
支持的类型:Number、String、Boolean、Array、Object、Function、Symbol
required:必填
default:默认值,当父组件不传值时,使用默认值
const app = Vue.createApp({
data(){
return{
message:'hello world',
num:"hello"
}
},
template:'<div>{{message}} <test ></test></div>',
});
app.component('test',{
props:{
num:{
type:String,
required:true,
default:"nihao"
}
},
template:`<div>{{ typeof num}}</div>`
})
app.mount('#app')
控制台:
vue@next:1312 [Vue warn]: Missing required prop: "num"
at <Test>
at <App>
validator验证
const app = Vue.createApp({
data(){
return{
message:'hello world',
num: 1235
}
},
template:'<div>{{message}} <test :num="num"></test></div>',
});
app.component('test',{
props:{
num:{
type:Number,
required:true,
default:520,
validator: function(num){
return num<1000;
}
}
},
template:`<div>{{ num }}</div>`
})
app.mount('#app')
此时传入的数是1235,大于1000,控制台报
[Vue warn]: Invalid prop: custom validator check failed for prop "num".
at <Test num=1235 >
at <App>