如何在Vuetify中实现按钮点击切换颜色文本、再次点击恢复原状态
解决方案
原有代码核心问题
- 数据结构定义错误:
state被定义为包含对象的数组,不符合状态存储需求;accountFeatures.equityTrading初始值错误赋值为整个state,而非状态字符串 - 状态判断逻辑错误:
accountFeaturesState方法中错误使用this.state[this.enabled]读取状态,实际不存在this.enabled这个实例属性 - 切换逻辑错误:
sendState方法未做状态切换判断,直接赋值为固定字符串,且注释中的判断逻辑使用了全等判断符号===做赋值操作
可直接运行的修改后代码
模板部分
<v-btn @click="sendState" :color="accountFeaturesState(accountFeatures.equityTrading)" > {{ accountFeatures.equityTrading }} </v-btn>
逻辑部分
export default { data: function () { return { // 定义状态常量统一管理取值,避免硬编码 STATE_CONST: { enabled: "Enabled", disabled: "Disabled" }, accountFeatures: { // 初始状态可根据需求调整为Enabled/Disabled equityTrading: "Enabled" } } }, methods: { accountFeaturesState(currentState) { return currentState === this.STATE_CONST.enabled ? "green" : currentState === this.STATE_CONST.disabled ? "red" : "grey" }, sendState() { // 点击时切换状态 this.accountFeatures.equityTrading = this.accountFeatures.equityTrading === this.STATE_CONST.enabled ? this.STATE_CONST.disabled : this.STATE_CONST.enabled } } } </script>
内容的提问来源于stack exchange,提问作者pandasruler
相关产品推荐
相关产品推荐

