Segmented分段控制器怎么实现点击切换样式?

夏侯新杰 阅读 5

我用Vue写了个分段控制器,但点选后active状态的样式没加上,不知道是哪出问题了?

试过给当前项加:class="{ active: currentIndex === index }",但页面上就是不生效。

<div class="segmented">
  <div 
    v-for="(item, index) in tabs" 
    :key="index"
    @click="currentIndex = index"
    :class="{ active: currentIndex === index }"
    class="tab"
  >
    {{ item }}
  </div>
</div>
我来解答 赞 6 收藏
二维码
手机扫码查看
1 条解答
西门书娟
问题大概率出在CSS优先级上,不是Vue代码的问题。

你那段模板代码写法没问题,:class 绑定是正确的。点击能触发 @click,说明数据响应式也在工作。

最常见的情况是:你给 .tab.active 都写了相同的样式属性(比如 backgroundcolor),但 .tab 的选择器优先级更高,把 .active 的样式覆盖了。

检查一下你的CSS,大概是这样:

.tab {
background: gray;
color: white;
}
.tab.active {
background: blue; /* 这个优先级更高 */
}


或者反过来,你可能写成了:

.tab {
background: gray;
}
.active {
background: blue; /* 如果HTML中class顺序问题,可能不生效 */
}


解决办法很简单,把 .active 的样式改成更具体的选择器:

.tab.active {
background: blue;
/* 其他active状态样式 */
}


这样即使 .tab 写在前面,tab.active 的优先级也足够覆盖它。

另外确保 currentIndex 在 data 里初始化了,比如 data() { return { currentIndex: 0 } }。没初始化的话有时候也会有奇怪的问题。
点赞
2026-03-13 13:02