vue实现switch开关
Vue实现Switch开关的方法
使用原生HTML和CSS实现
通过HTML的<input type="checkbox">结合CSS样式可以快速实现Switch开关效果。
<template>
<label class="switch">
<input type="checkbox" v-model="isChecked">
<span class="slider round"></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;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
使用第三方UI库
主流UI库如Element UI、Vuetify等都已封装好Switch组件,可直接使用。
Element UI示例:
<template>
<el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
</template>
<script>
export default {
data() {
return {
value: true
}
}
}
</script>
Vuetify示例:
<template>
<v-switch v-model="switchValue" :label="`Switch: ${switchValue.toString()}`"></v-switch>
</template>
<script>
export default {
data() {
return {
switchValue: false
}
}
}
</script>
自定义可复用组件
创建独立的Switch组件,提高代码复用性。
<!-- Switch.vue -->
<template>
<label class="custom-switch">
<input type="checkbox" v-model="modelValue" @change="$emit('update:modelValue', $event.target.checked)">
<span class="custom-slider" :class="{ 'active': modelValue }"></span>
</label>
</template>
<script>
export default {
props: {
modelValue: Boolean
},
emits: ['update:modelValue']
}
</script>
<style>
/* 自定义样式 */
</style>
使用方式:
<template>
<Switch v-model="isActive" />
</template>
<script>
import Switch from './Switch.vue'
export default {
components: { Switch },
data() {
return {
isActive: false
}
}
}
</script>
添加动画效果
通过CSS过渡或动画增强交互体验。
.slider {
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.slider:before {
transition: all 0.3s ease-in-out;
}
input:checked + .slider {
box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
}
添加禁用状态
扩展组件功能,支持禁用状态。

<template>
<label class="switch" :class="{ 'disabled': disabled }">
<input type="checkbox" v-model="modelValue" :disabled="disabled">
<span class="slider"></span>
</label>
</template>
<script>
export default {
props: {
modelValue: Boolean,
disabled: Boolean
}
}
</script>
<style>
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>






