VueJS - Object Props validation(VueJS - 对象道具验证)
问题描述
在 VueJS 中,如何验证 Object 类型的 props 以确保该对象定义了一些特定的字段?
In VueJS, how can I validate Object type props in order to ensure that the object has some specific fields defined?
例如,我想确保用户道具将具有姓名"、出生日期"等字段.
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#道具验证
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 - 对象道具验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:VueJS - 对象道具验证
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
