vue实现开关
Vue 实现开关组件的方法
使用原生 HTML 和 Vue 数据绑定
通过 v-model 绑定复选框的选中状态,利用 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 库
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>
Ant Design Vue 的开关组件:

<template>
<a-switch v-model:checked="checked" />
</template>
<script>
export default {
data() {
return {
checked: false
}
}
}
</script>
自定义可复用的开关组件
创建可复用的开关组件,支持自定义样式和事件:
<!-- 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>
<span class="label">{{ label }}</span>
</label>
</template>
<script>
export default {
props: {
modelValue: Boolean,
label: String
},
emits: ['update:modelValue']
}
</script>
<style>
/* 自定义样式 */
</style>
使用自定义组件:

<template>
<Switch v-model="isActive" label="启用功能" />
</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.3);
}
.slider:before {
/* 原有样式 */
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
input:checked + .slider {
/* 原有样式 */
box-shadow: 0 0 1px #2196F3;
}
无障碍支持
增加 ARIA 属性提升可访问性:
<label class="switch">
<input
type="checkbox"
v-model="isChecked"
role="switch"
:aria-checked="isChecked"
:aria-label="isChecked ? '开启' : '关闭'"
>
<span class="slider"></span>
</label>






