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
相关产品推荐
相关产品推荐

