子组件接收父组件的参数的时候,props注册接收的参数
props:['count']子组件可以对接收的参数校验。
例如规定接收的count参数要求是String
props:{
count:String
}如果count是别的类型就会报错
组件的参数校验
组件的参数校验指的是什么呢?你父组件向子组件传递的内容,子组件有权对这个内容进行一些约束,这个约束我们可以把它叫做参数的校验。
<div id="root">
<child content="hello world"></child>
</div>
Vue.component('child',{
props: ['content'],
template: '<div>{{content}}</div>'
})
let vm = new Vue({
el: '#root',
})现在有这样一个需求,父组件调用子组件的时候,传递的这个
content,我要做一些约束,要求它我传递过来的
content必须是一个字符串,我们该怎么实现呢?
<div id="root">
<child content="hello world"></child>
</div>
Vue.component('child',{
props: {
content: String //子组件接收到的 content 这个属性,必须是一个字符串类型的
},
template: '<div>{{content}}</div>'
})
let vm = new Vue({
el: '#root',
})组件接收到的
content这个属性,必须是一个字符串类型的,如果我需要的参数类型是字符串或者数组,又该怎么写呢?
props: {
content: [ String, Number ]},
content的类型,可以用数组来表示。
content其实还有更复杂的用法:
props: {
content: {
type: Sring,
required: true, //必传
default: 'default value', //默认显示,非必传会显示
validator(value){ //检测 content 的长度,如果长度大于 5,正常显示,如果长度小于 5 则报错
return (value.length > 5)
}
}
}非props特性
说到非
props特性,它一定和
props特性相对应。
props特性:当你的父组件使用子组件的时候,通过属性向子组件传值的时候,恰好子组件里面声明了对父组件传递过来的属性的一个接收,也就是说父子组件有个对应关系,如果你这么写我们就把叫做










