共计 1233 个字符,预计需要花费 4 分钟才能阅读完成。
组件的参数校验
组件的参数校验指的是什么呢?你父组件向子组件传递的内容,子组件有权对这个内容进行一些约束,这个约束我们可以把它叫做参数的校验。
<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 特性:当你的父组件使用子组件的时候,通过属性向子组件传值的时候,恰好子组件里面声明了对父组件传递过来的属性的一个接收,也就是说父子组件有个对应关系,如果你这么写我们就把叫做 props 特性
props 特性的特点是,如下图:
我们在子组件里有一个 content 的内容传递,这个属性的内容传递是不会在 dom 标签上进行显示的。
当你父组件传递了 content,你子组件接收了这个 content,你在模版里就可以直接通过插值表达式或者通过 this.content,去取得 content 里面的内容了。
非 props 特性:父组件向子组件传递了一个属性,但是子组件并没有 props 这块的内容,也就是说子组件并没有声明我要接收父组件的传递过来的内容
非 props 特点:
非 props 特性在子组件里面,没办法获取到你父组件传递的内容,因为你压根没声明你要获取的内容,也就没法用。
如果我们用的是非 props 特性,那么这个特性是会显示在 dom 标签上的