重写Vue组件,使其更加DRY



我只是想寻求一些建议,如果有更有效的方法来写下面的内容,让它变得更干燥一点?

<h2>{{ title }}</h2>
<p>{{ subtitle }}</p>

当我在标题和副标题上对这个.name进行同样的检查时,我认为可能有一种比我目前的实现方式更好的方法,有什么想法吗?

computed: {
title() {
if (this.name === 'discounts_offers') {
return this.$t('discounts.title')
}
if (this.name === 'newsletter') {
return this.$t('newsletters.title')
}
if (this.name === 'product_upgrade') {
return this.$t('upgrade.title')
}
return this.name
},
subtitle() {
if (this.name === 'discounts_offers') {
return this.$t('discounts.subtitle')
}
if (this.name === 'newsletter') {
return this.$t('newsletters.subtitle')
}
if (this.name === 'product_upgrade') {
return this.$t('upgrade.subtitle')
}
return this.name
},
}

我的建议:

文字键应与this.name的值相同。这样你就可以动态地翻译它们。

因此,而不是多个if/else子句。您可以通过一行代码直接实现这一点。

title() {
return this.$t(this.name)
}

这样的东西怎么样?

data() {
return {
map: {
discounts_offers: "discounts",
newsletter: "newsletters",
product_upgrade: "upgrade"
}
}
},
computed: {
title() {
return this.map[this.name] ? this.$t(`${this.map[this.name]}.title`) : this.name
},
subtitle() {
return this.map[this.name] ? this.$t(`${this.map[this.name]}.subtitle`) : this.name
},
}

最新更新