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

如何实现点击v-chip切换颜色、再次点击还原原有颜色的效果

v-chip点击切换颜色实现方案

核心逻辑是在颜色绑定方法中传入当前chip对应的值,判断其是否在选中数组中,返回对应的颜色即可实现点击切换效果。

步骤1:修正JS逻辑

原代码存在两处语法错误,同时调整颜色判断方法的逻辑:

  • data返回的对象属性用冒号赋值,不是等号
  • methods为对象属性,用冒号声明
data () {
   return {
     restrictions: ['Restriction 1','Restriction 2','Restriction 3','Restriction 4'],
     selectedRestrictions: []
   }
},
methods: {
  // 接收当前chip对应的restriction作为参数
  handleChipColor(restriction){
    // 判断当前项是否在选中数组中,是则返回选中色,否则返回默认色
    return this.selectedRestrictions.includes(restriction) ? 'primary' : 'grey lighten-2'
  },
  selectRestriction(restriction){
      const el = this.selectedRestrictions.findIndex(el => el === restriction);
      el < 0 ? this.selectedRestrictions.push(restriction) : this.selectedRestrictions.splice(el,1);
    }
}

步骤2:修改模板绑定

在:color绑定处传入当前遍历的restriction参数:

<v-chip 
  class="margin" 
  :color="handleChipColor(restriction)" 
  v-for="restriction in restrictions"  
  @click="selectRestriction(restriction)" 
  :key="restriction"
>
  {{restriction}}
</v-chip>

逻辑说明

每次点击触发selectRestriction更新选中数组后,Vue响应式机制会自动重新计算所有chip的handleChipColor返回值,对应颜色会自动更新,无需额外操作DOM。如果需要自定义选中色/默认色,直接修改handleChipColor里的返回值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:15:07