Vue3 代码优化:使用计算属性简化逻辑判断
computed: {
// 获取下一期游戏的状态标签
nextGameLabel() {
const nextGame = this.resdata.nextGame;
if (!nextGame) {
return "";
} else if (nextGame.now > nextGame.startTime) {
return "开奖中";
} else {
return "马上参与";
}
}
},
methods: {
// 获取按钮样式
buttonClass(index) {
const state = index.state;
if (state === 0) {
return "btn-danger";
} else if (state === 1) {
return "btn-border-default";
} else if (this.resdata.nextGame.now > index.stopTime) {
return "btn-border-warning";
} else {
return "";
}
},
// 获取按钮标签
buttonLabel(index) {
const state = index.state;
if (state === 1) {
return "已开奖";
} else if (state === 0 && this.resdata.nextGame.now > index.stopTime) {
return "开奖中";
} else {
return this.nextGameLabel;
}
}
}
这样做的好处是,将逻辑判断从模板中移出,使得模板更加简洁易读。同时,计算属性可以帮助我们缓存结果,避免重复计算。
原文地址: https://www.cveoy.top/t/topic/lDpU 著作权归作者所有。请勿转载和采集!