Javascript VueJS-对象道具验证
在VueJS中,如何验证对象类型道具以确保该对象定义了某些特定字段 例如,我想确保用户道具将包含“name”、“birthDate”等字段Javascript VueJS-对象道具验证,javascript,vue.js,components,Javascript,Vue.js,Components,在VueJS中,如何验证对象类型道具以确保该对象定义了某些特定字段 例如,我想确保用户道具将包含“name”、“birthDate”等字段 提前感谢。您可以为对象创建自定义验证程序功能: 如果所有字段都存在,函数应返回true 例如: Vue.component('子'{ 模板:`{myprop.id}}{{myprop.name}}`, 道具:{ myprop:{ 验证器:函数(obj){ 返回(obj.id&&Number.isInteger(obj.id)&&obj.name&&obj
提前感谢。您可以为对象创建自定义验证程序功能: 如果所有字段都存在,函数应返回
true
例如:
Vue.component('子'{
模板:`{myprop.id}}{{myprop.name}}`,
道具:{
myprop:{
验证器:函数(obj){
返回(obj.id&&Number.isInteger(obj.id)&&obj.name&&obj.name.length);
}
}
}
});
新Vue({
el:“#应用程序”,
数据:{
myObj:{
id:10,
名字:“乔”
}
}
});
如果验证器失败,您将在浏览器控制台中看到一个
Vue warn
。下面是我为一个类似的案例编写的验证器示例,用于属性传递屏幕上显示和隐藏的项目的显示延迟(毫秒)。在这种情况下,属性可以是“显示”和“隐藏”的数字,也可以是为每种情况定义不同延迟的对象
我检查每个键的类型,以确保它与我的情况下的“number”匹配。如果缺少键,则类型将为“未定义”。在我的例子中,负值是不允许的
props: {
delay: {
type: [Number, Object],
default: 0,
validator(value) {
if (typeof value === 'number') {
return value >= 0;
} else if (value !== null && typeof value === 'object') {
return typeof value.show === 'number' &&
typeof value.hide === 'number' &&
value.show >= 0 &&
value.hide >= 0;
}
return false;
}
},
}
像这样的可能-当然你可以用更优雅的方式来检查属性我在我的答案中添加了一个例子。
<div id="app">
<child :myprop="myObj"></child>
</div>
Vue.component('child', {
template: `<span>{{ myprop.id }} {{ myprop.name }}</span>`,
props: {
myprop: {
validator: function(obj) {
return (obj.id && Number.isInteger(obj.id) && obj.name && obj.name.length );
}
}
}
});
new Vue({
el: '#app',
data: {
myObj: {
id: 10,
name: 'Joe'
}
}
});
props: {
delay: {
type: [Number, Object],
default: 0,
validator(value) {
if (typeof value === 'number') {
return value >= 0;
} else if (value !== null && typeof value === 'object') {
return typeof value.show === 'number' &&
typeof value.hide === 'number' &&
value.show >= 0 &&
value.hide >= 0;
}
return false;
}
},
}