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 - 对象道具验证
				
        
 
            
        - Fetch API 如何获取响应体? 2022-01-01
 - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - 400或500级别的HTTP响应 2022-01-01
 - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - Flexslider 箭头未正确显示 2022-01-01
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - addEventListener 在 IE 11 中不起作用 2022-01-01
 - 失败的 Canvas 360 jquery 插件 2022-01-01
 
						
						
						
						
						