记录生活中的点滴,分享、学习、创新
prop 传值检验规则
如果是 prop 是静态传值,则必须是 String 类型
如果是 prop 是动态传值,则可以验证任意类型
示例,如果必须要传一个Number,就必须使用 bind
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //声明 Vue.component( "blog-post" , { props: { postTitle: { type: Number, default : 10000 } }, template: "<h3>{{ postTitle }}</h3>" }); //在template中调用,静态传值,值必定是 String <blog-post postTitle= "54" ></blog-post> //在template中调用,动态传值,值可以是 String、Number、Boolen。。。 <blog-post :postTitle= "54" ></blog-post> |
类型检查的 type 值,可以是下列原生构造函数中的一个:
String
Number
Boolean
Array
Object
Date
Function
Symbol
type 还可以是一个自定义的构造函数,并且通过 instanceof 来进行检查确认。
示例:
1 2 3 4 5 6 7 8 9 10 11 | //例如,给定下列现成的构造函数: function Person (firstName, lastName) { this .firstName = firstName this .lastName = lastName } //可以使用,检验是否为 Person 的实例 Vue.component( 'blog-post' , { props: { author: Person } }) |
补充知识:vue中prop验证、类型检查及注意事项
1、注意:null和undefined会通过任何类型检测
2、数组或对象类型需要提供默认值的话需要通过函数返回。详情看这里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | props:{ // 数组或对象的默认值需要通过函数返回 authInfo:{ type:Object, default (){ return { name: '张三' , sex:0 } } }, list:{ type:Array, default (){ return [ 1,2,3 ] } } } |
3、使用自定义函数验证
1 2 3 4 5 6 7 | props:{ address:{ validator(value){ return [ '黑龙江' , '吉林' , '辽宁' ].indexOf(value) !== -1 } } } |
4、非prop的特性:若一个属性传向一个组件,但是该组件并没有定义相应 prop。则该属性称为非prop特性。非prop特性会作用到组件的根元素上。
若非prop中含有组件跟元素定义的属性。则非prop中的值会覆盖组件定义的值(这种情况称作 非prop继承)。style和class例外,它们会发生合并。
不希望非prop继承该怎么办?
如果不希望非prop自动作用到组件的根元素上可以在vue的组件选项里添加 inheritAttrs选项(此选项无法影响class和style的绑定)。
inheritAttrs:false
inheritAttrs属性可以和$attrs配合可以是非prop作用到开发者想作用到的元素上。而不作用的根元素上。例:
1 2 3 4 5 6 7 8 9 10 11 | <template> <div> <input type= "text" v-bind= "$attrs" > <!--将非prop绑定到此元素--> </div> </template> <script> export default { name: "sg-test" , inheritAttrs: false , //禁止 非prop继承 } </script> |
以上这篇vue prop传值类型检验方式就是小编分享给大家的全部内容了,希望能给大家一个参考