Default values for Vue component props & how to check if a user did not set the prop?

PeraMika picture PeraMika · Nov 1, 2016 · Viewed 97.9k times · Source

1. How can I set the default value for a component prop in Vue 2? For example, there is a simple movies component that can be used in this way:

<movies year="2016"><movies>



Vue.component('movies', {
    props: ['year'],

    template: '#movies-template',
    ...
}

But, if a user doesn't specify the year:

<movies></movies>

then the component will take some default value for the year prop.

2. Also, what is the best way to check if a user did not set the prop? Is this a good way:

if (this.year != null) {
    // do something
}

or maybe this:

if (!this.year) {
    // do something
}

?

Answer

craig_h picture craig_h · Nov 1, 2016

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/