本文实例为大家分享了vue.js组件props数据验证的具体代码,供大家参考,具体内容如下
数据验证
一般当组件需要提供给别人使用时,就需要使用数据验证。
示例:
<script>
vue.component('my-component',{
props:{
//必须是数字类型
propA: Number,
//必须是字符串或数字类型
propB:[String, Number],
//布尔值,如果没有定义,默认值就是true
propC:{
type: Boolean,
default: true
},
//数字,而且是必选
propD: {
type: Number,
required: true
},
//如果是数组或对象,默认值必须是一个函数来返回
propE: {
type: Array,
default: function () {
return {};
}
},
//自定义验证函数
propF: {
viladator: function (value) {
return value > 10;
}
}
}
});
</script>
验证的type类型可以是:
- String
- Number
- Boolean
- Object
- Array
- Function
type也可以是一个自定义构造器,使用instanceof检测。当prop验证失败时,开发版本下会在控制台抛出一条警告。
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://unpkg.com/vue/dist/vue.js"></script> <title>组件:参数验证</title> </head> <body> <!--为组件中接受到的变量进行逻辑验证--> <div id="myApp"> <h1>身世之谜</h1> <show-member-info name="koma" :age="25" :detail="{address:'earth',language:'世界语'}"></show-member-info> </div> <script> Vue.component('show-member-info',{ props: { name: { type: String,//类型 required: true,//必选,不选报错 }, age: { type: Number, validator: function (value) { return value >= 0 && value <=130; } }, detail: { type: Object, default: function () { return { address: 'US', language: 'English' }; } } }, template: '<div>姓名:{{this.name}}<br/>' + '年龄:{{this.age}}岁<br/>' + '地址:{{this.detail.address}}<br/>' + '语言:{{this.detail.language}}</div>' }); var myApp = new Vue({ el: '#myApp' }); </script> </body> </html>
更多教程点击《Vue.js前端组件学习教程》,欢迎大家学习阅读。
关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持前端开发者。
评论前必须登录!
注册