I. Preface
The previous article introduced how to implement parameter passing through the props option of components This section will introduce the data verification of parameters through props
2, Use of props data validation
The value of component props option can be array type or object type The object type of props option can be used for data validation of parameters passed in externally When we encapsulate a component for others to use, it is very necessary to verify the parameters received internally
<div id="app">
<lable>Number:</lable>
<input type="text" v-model="parentInput" placeholder="Please input...">
<my-component :prop-a="parentInput"></my-component>
</div>
<script type="text/javascript">
Vue.component('my-component',{
props:{
// Number type
propA: Number,
// Multiple types of verification: String or Number
propB: [String, Number],
// Boolean type, default true
propC:{
type:Boolean,
default: true
},
// String type and required
propD:{
type:String,
required: true
},
// Array type, return an array object by default
propE:{
type:Array,
default: function () {
return [1,2,3]
}
},
// Object type, return an object by default
propF:{
type:Object,
default: function () {
return {a:1}
}
},
// Custom validation function
propG:{
validator:function (value) {
return value < 10;
}
},
}
});
const vm = new Vue({
el: '#app',
data:{
parentInput:0
}
})
</script>
When the input of test Number type is String type:
When the input type does not conform to the verification, the console will throw a warning message
We can verify the following data types:
String Number Boolean Object Array Function type Can make a custom constructor,Use instanceof Verify //A warning will be thrown in the console when the verification of prop s fails in the development version
3, Precautions
Since props is verified before the component instance is created, So in the default or validator function, if there are options such as data, computed or methods, It will not be available at this time
Four, ending
This is how to verify the parameters of props, and component communication will be introduced later