vue实现开关
Vue 实现开关组件的方法
使用原生HTML和Vue数据绑定
通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果:
<template>
<label class="switch">
<input type="checkbox" v-model="isChecked">
<span class="slider"></span>
</label>
</template>
<script>
export default {
data() {
return {
isChecked: false
}
}
}
</script>
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
</style>
使用第三方UI库
Vuetify、Element UI等流行UI库提供了现成的开关组件:
Vuetify示例:
<template>
<v-switch v-model="isActive" label="开关状态"></v-switch>
</template>
Element UI示例:
<template>
<el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
</template>
自定义可复用开关组件
创建可复用的开关组件,支持自定义样式和事件:
<!-- ToggleSwitch.vue -->
<template>
<label :class="['toggle-switch', { 'disabled': disabled }]">
<input
type="checkbox"
v-model="internalValue"
:disabled="disabled"
@change="$emit('change', internalValue)"
>
<span class="switch-track" :style="trackStyle">
<span class="switch-thumb" :style="thumbStyle"></span>
</span>
</label>
</template>
<script>
export default {
props: {
value: Boolean,
disabled: Boolean,
activeColor: {
type: String,
default: '#4CAF50'
},
inactiveColor: {
type: String,
default: '#9E9E9E'
}
},
computed: {
internalValue: {
get() { return this.value },
set(val) { this.$emit('input', val) }
},
trackStyle() {
return {
backgroundColor: this.internalValue ? this.activeColor : this.inactiveColor
}
},
thumbStyle() {
return {
transform: this.internalValue ? 'translateX(20px)' : 'translateX(0)'
}
}
}
}
</script>
动画增强效果
为开关添加更流畅的动画效果:
.switch-track {
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.switch-thumb {
transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
无障碍支持
增强开关的无障碍访问能力:
<label class="switch">
<input
type="checkbox"
v-model="isChecked"
role="switch"
:aria-checked="isChecked"
aria-labelledby="toggle-label"
>
<span class="slider"></span>
</label>
<span id="toggle-label">夜间模式</span>






