vue switch开关实现
Vue Switch 开关实现方法
在 Vue 中实现开关(Switch)功能可以通过多种方式完成,以下是几种常见的方法:
使用原生 HTML 和 Vue 数据绑定
通过结合 <input type="checkbox"> 和 Vue 的 v-model 实现基础开关:
<template>
<label class="switch">
<input type="checkbox" v-model="isChecked">
<span class="slider round"></span>
</label>
<p>当前状态: {{ isChecked ? '开启' : '关闭' }}</p>
</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-text="开" inactive-text="关">
</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: true
}
}
}
</script>
自定义可复用 Switch 组件
创建可复用的 Switch 组件:
<!-- Switch.vue -->
<template>
<label class="custom-switch">
<input
type="checkbox"
:checked="modelValue"
@change="$emit('update:modelValue', $event.target.checked)"
>
<span class="custom-slider" :class="{ 'active': modelValue }"></span>
</label>
</template>
<script>
export default {
props: {
modelValue: {
type: Boolean,
default: false
}
},
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>
动画效果增强
为开关添加更丰富的动画效果:

.slider {
/* 基础样式... */
box-shadow: 0 0 1px rgba(0,0,0,0.5);
}
.slider:before {
/* 基础样式... */
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
input:checked + .slider {
box-shadow: inset 0 0 10px rgba(33,150,243,0.5);
}
以上方法可以根据项目需求选择使用,从简单实现到完整组件化方案均可满足不同场景。






