Vue.js中优化显示消费金额和次数的代码示例
本文将介绍如何优化Vue.js中显示消费金额和次数的代码,并提供具体的代码示例。
原始代码中存在大量重复代码,我们可以通过使用计算属性来简化代码逻辑。
**代码优化示例:**
首先,创建一个计算属性来计算需要显示的label和value:
computed: {
label() {
if (this.form.cardType == 0 && this.form.consumptionType == 1) {
return '消费金额';
} else if (this.form.cardType == 1 && this.form.consumptionType == 1) {
return '消费次数';
} else if (this.form.cardType == 0 && this.form.consumptionType == 0) {
return '充值金额';
} else if (this.form.cardType == 1 && this.form.consumptionType == 0) {
return '充值次数';
} else {
return '';
}
},
value() {
if (this.form.cardType == 0 && this.form.consumptionType == 1) {
return this.form.costAmount + ' 元';
} else if (this.form.cardType == 1 && this.form.consumptionType == 1) {
return this.form.costTimes + ' 次';
} else if (this.form.cardType == 0 && this.form.consumptionType == 0) {
return this.form.costAmount + ' 元';
} else if (this.form.cardType == 1 && this.form.consumptionType == 0) {
return this.form.costTimes + ' 次';
} else {
return '';
}
}
}
然后,在模板中使用计算属性来显示label和value:
<el-descriptions-item v-if="label" :label="label" labelStyle="background: #F5F7FA;">{{ value }}</el-descriptions-item>
通过使用计算属性和简化代码逻辑,可以优化重复代码的问题。
原文地址: https://www.cveoy.top/t/topic/qjHY 著作权归作者所有。请勿转载和采集!