VueJS - 对象道具验证 [英] VueJS - Object Props validation

查看:26
本文介绍了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 - 对象道具验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆