What are props? In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components. When we build our applications out of components, we end up building a data structure called a tree.
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/
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.
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' }
}
},
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With