VueJS Using Prop Type Validation With NULL and 'undefined' Values? VueJS Using Prop Type Validation With NULL and 'undefined' Values? vue.js vue.js

VueJS Using Prop Type Validation With NULL and 'undefined' Values?


// Basic type check (null and undefined values will pass any type validation)

This applies only when required: true is NOT set. In your code, you are saying that the prop is required and so Vuejs is showing the warning

Related discussion: https://forum.vuejs.org/t/shouldnt-null-be-accepted-as-prop-value-with-any-type/63887


It's because of required: true

From API docs (more detail)

required: Boolean Defines if the prop is required. In a non-production environment, a console warning will be thrown if this value is truthy and the prop is not passed.


As Cato mentioned using a validator can help solve this issue.

You will need to provide a default and make sure required is not set or is false.

<script>Vue.component('MyInput', Vue.extend({    props: {        value: {            type: [String, Number, Boolean],            default: null,            validator: (p) => {                return ['string', 'number', 'boolean'].indexOf(typeof p) !== -1 || p === null;            },        }    }});</script>

This may look like it will work the same as this...

<script>Vue.component('MyInput', Vue.extend({    props: {        value: {            type: [String, Number, Boolean],            required: false,            default: null,        }    }});</script>

However, in the second example you can pass undefined. In the first you can pass the listed types plus null.