190

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
}

?

PeraMika
  • 3,539
  • 9
  • 38
  • 63

4 Answers4

336

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/

craig_h
  • 31,871
  • 6
  • 59
  • 68
  • 2
    What about second question (this is more JavaScript question): what is the best way to check if a user did not set the prop? Is this a good way: `if (this.year != null)` or maybe this: `if (!this.year)` or? Thanks! – PeraMika Nov 01 '16 at 19:43
  • 1
    If you set a default value the prop will always be set unless you set the default to `null`. If that is what you need to perform some other logic `if (this.year != null)` or `if (!this.year)` is the way to go. – craig_h Nov 01 '16 at 20:30
51

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

aurumpotestasest
  • 766
  • 7
  • 18
  • 3
    This was a great strategy in Vue 2. Unfortunately `this.$options.propsData` is removed in Vue 3. Is there another way to check if a prop has been explicitly passed in? – supertrue Nov 16 '21 at 03:54
8

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },
LastM4N
  • 1,890
  • 1
  • 16
  • 22
5

Worth mentioning, that you also can add a custom validator function to every prop like this, to ensure the passed value matches your components specific requirements:

props: {
  year: {
    type: Number,
    required: true
    validator (value) {
      return value > 2015
    }
  }
}
tho-masn
  • 1,126
  • 1
  • 7
  • 13