Vue 组件 props & 的默认值如何检查用户是否没有设置道具? [英] Default values for Vue component props & how to check if a user did not set the prop?
问题描述
1. 如何在 Vue 2 中为组件 prop 设置默认值?例如,有一个简单的 movies
组件可以这样使用:
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',
...
}
但是,如果用户没有指定year
:
But, if a user doesn't specify the year
:
<movies></movies>
然后组件将为 year
属性取一些默认值.
then the component will take some default value for the year
prop.
2. 另外,检查用户是否没有设置道具的最佳方法是什么?这是一个好方法吗:
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
}
或者这个:
if (!this.year) {
// do something
}
?
推荐答案
Vue
允许您指定默认的 prop
值和 type
直接,通过使道具成为一个对象(参见:https://vuejs.org/guide/components.html#Prop-Validation):
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/
这篇关于Vue 组件 props & 的默认值如何检查用户是否没有设置道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!