VueJS - 对象道具验证 [英] VueJS - Object Props validation
本文介绍了VueJS - 对象道具验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在VueJS中,我如何验证对象类型道具以确保对象定义了一些特定字段?
In VueJS, how can I validate Object type props in order to ensure that the object has some specific fields defined?
例如,我想确保user prop将包含字段'name','birthDate'等。
For example, i want to ensure that the user prop will have the fields 'name', 'birthDate', and so on.
提前致谢。
推荐答案
您可以为对象创建自定义验证器函数:
You can create a custom validator function for objects:
https://vuejs.org/v2/guide/components.html#Prop-Validation
props: {
propF: {
validator: function (value) {
return value > 10
}
}
}
函数应返回 true
如果所有字段都存在。
Function should return true
if all fields are present.
示例: https://jsfiddle.net/wostex/63t082p2/27/
<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'
}
}
});
如果验证器失败,您将看到 Vue警告
在浏览器控制台中。
If validator fails you will see a Vue warn
in browser console.
这篇关于VueJS - 对象道具验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文