You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js实现点击标签激活时修改文本颜色的方法

标签栏激活状态文本变红的解决方案

你的代码存在两个核心问题:动态类的判断逻辑错误,且第二个标签未配置激活状态的类绑定。以下是修正后的实现:

修正后的组件代码

<template>
  <div>
    <div 
      @click="visibleComponent='transactions'"
      :class="[
        'font-weight-400 font-size-16 line-height-24',
        visibleComponent === 'transactions' ? 'red' : 'white'
      ]"
    >
      Wallet
    </div>
    <div 
      @click="visibleComponent='bankAccount'"
      :class="[
        'font-weight-400 font-size-16 line-height-24 padding-left-20',
        visibleComponent === 'bankAccount' ? 'red opacity-100' : 'blue opacity-25'
      ]"
    >
      Bank Account
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      visibleComponent: 'transactions' // 默认激活第一个标签
    }
  }
}
</script>

<style scoped>
.red {
  color: red;
}
.opacity-100 {
  opacity: 1;
}
/* 其他基础样式如果已在全局定义可忽略 */
.font-weight-400 { font-weight: 400; }
.font-size-16 { font-size: 16px; }
.line-height-24 { line-height: 24px; }
.white { color: white; }
.blue { color: blue; }
.opacity-25 { opacity: 0.25; }
.padding-left-20 { padding-left: 20px; }
</style>

关键修改说明

  • 动态类绑定使用数组语法,将基础样式和条件样式分离,逻辑更清晰
  • 判断条件改为visibleComponent === '对应值',匹配时应用red类实现文本变红
  • 第二个标签激活时移除opacity-25并添加opacity-100,保证激活状态视觉辨识度
  • 补充默认的visibleComponent值,确保页面初始化时有明确的激活标签

内容的提问来源于stack exchange,提问作者jibzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:30:49