VueJS - Object Props validation

2019-06-16 09:43发布

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.

Thanks in advance.

2条回答
beautiful°
2楼-- · 2019-06-16 09:53

Here is an example validator I wrote for one similar case for a property to communicate a display delay for an item that appears on and hides from the screen, in milliseconds. In this case, the property can either be a number for both the "show" and "hide", or it can be an object which defines different delays for each case.

I check the type each key I am expecting to make sure it matches, in my case, 'number'. If a key is missing then the type will be 'undefined'. In my case, negative values are not allowed.

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;
        }
    },
}
查看更多
女痞
3楼-- · 2019-06-16 09:57

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
     }
   }
}

Function should return true if all fields are present.

Example: 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'
      }
    }
});

If validator fails you will see a Vue warn in browser console.

查看更多
登录 后发表回答