Vuetify2.4如何自定义v-switch激活/未激活状态颜色
Vuetify 2.x v-switch 组件双状态自定义配色实现方案
核心问题说明
v-switch 原生提供的 color 属性仅支持配置开关开启状态的主题色,关闭状态默认使用全局灰色样式。如果选择器写得过于宽泛,会出现样式覆盖不全的问题:仅能修改外围涟漪光晕颜色,滑块填充色、滑轨背景色无法按预期修改。
最终实现效果
- 开启状态:使用配置的
blue darken-2蓝色,滑块、滑轨、涟漪光晕效果完全匹配 - 关闭状态:使用自定义紫色(色值
#6A1B9A,对应purple darken-2),滑块、滑轨、涟漪光晕效果完全匹配 - 两侧说明文字颜色随开关状态自动切换,和原有交互逻辑一致
完整实现代码
模板部分
移除原有v-switch上多余的value="error"属性(布尔值绑定v-model时不需要额外配置value,否则会导致状态匹配异常):
<div id="app"> <v-app id="inspire"> <v-card flat> <v-card-text> <v-container fluid> <v-row> <div class="d-flex"> <p class="mr-1 my-auto" :class="!myswitch?'purple--text text--darken-2 font-weight-bold':'grey--text'" > My off Value </p> <v-switch v-model="myswitch" color="blue darken-2" hide-details class="mt-n1 custom-switch" ></v-switch> <p class="mx-auto my-auto" :class="myswitch?'blue--text text--darken-2 font-weight-bold':'grey--text'" > My on Value </p> </div> </v-row> </v-container> </v-card-text> </v-card> </v-app> </div>
脚本部分
new Vue({ el: '#app', vuetify: new Vuetify(), data: () => ({ myswitch: false // 开关初始状态 }) })
样式部分
精准命中v-switch的滑块、滑轨、涟漪三个核心元素的类名,通过选中状态类名区分双状态样式优先级:
/* 关闭状态自定义紫色样式 */ .custom-switch .v-input--selection-controls__ripple, .custom-switch .v-input--switch__thumb, .custom-switch .v-input--switch__track { color: #6A1B9A !important; } /* 关闭状态滑轨透明度和原生交互逻辑保持一致 */ .custom-switch .v-input--switch__track { opacity: 0.38; } /* 选中状态下优先使用color属性配置的蓝色,避免被自定义紫色覆盖 */ .custom-switch.v-input--is-label-active .v-input--selection-controls__ripple, .custom-switch.v-input--is-label-active .v-input--switch__thumb, .custom-switch.v-input--is-label-active .v-input--switch__track { color: inherit !important; opacity: 1; }
适配说明
- 如果是在Vue单文件组件的
scoped样式块中编写上述样式,需要使用深度选择器穿透组件作用域,将所有.custom-switch后的选择器用::v-deep标记即可,示例:
<style scoped> .custom-switch::v-deep .v-input--selection-controls__ripple, .custom-switch::v-deep .v-input--switch__thumb, .custom-switch::v-deep .v-input--switch__track { color: #6A1B9A !important; } /* 其余样式按相同规则添加::v-deep即可 */ </style>
- 如果需要修改配色,直接替换关闭状态色值
#6A1B9A、开启状态修改v-switch上的color属性为任意Vuetify内置主题色或自定义色值即可。
内容的提问来源于stack exchange,提问作者floprm
相关产品推荐
相关产品推荐

