我只是在尋找一些關于是否有更有效的方法來撰寫以下內容的建議,讓它更干一點?
<h2>{{ title }}</h2>
<p>{{ subtitle }}</p>
當我在標題和副標題上對 this.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
},
}
uj5u.com熱心網友回復:
我的建議 :
文字鍵應與 的值相同this.name。這樣您就可以動態翻譯它們。
因此,而不是多個 if/else 子句。您可以通過一行代碼直接實作這一點。
title() {
return this.$t(this.name)
}
uj5u.com熱心網友回復:
這樣的事情怎么樣?
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
},
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/455349.html
標籤:javascript Vue.js
上一篇:使用vue在螢屏上更新變數
