admin管理员组文章数量:1131676
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>
Vueponent('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
}
?
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
}
?
Share Improve this question edited Jan 14, 2019 at 14:08 PeraMika asked Nov 1, 2016 at 17:52 PeraMikaPeraMika 3,68811 gold badges41 silver badges70 bronze badges4 Answers
Reset to default 342Vue
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
}
}
}
本文标签:
版权声明:本文标题:javascript - Default values for Vue component props & how to check if a user did not set the prop? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736779045a1952494.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论