vue 实现toggle效果
使用 v-model 实现基础 Toggle
在 Vue 中可以通过 v-model 绑定到复选框来实现 toggle 效果。这种方法适合简单的开关场景。
<template>
<label class="toggle">
<input type="checkbox" v-model="isActive">
<span class="slider"></span>
</label>
</template>
<script>
export default {
data() {
return {
isActive: false
}
}
}
</script>
<style>
.toggle {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.toggle 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>
使用自定义组件实现 Toggle
创建可复用的 toggle 组件,通过 props 和 emits 实现父子组件通信。
<!-- ToggleSwitch.vue -->
<template>
<label class="toggle-switch">
<input
type="checkbox"
:checked="modelValue"
@change="$emit('update:modelValue', $event.target.checked)"
>
<span class="slider round"></span>
</label>
</template>
<script>
export default {
props: {
modelValue: {
type: Boolean,
default: false
}
},
emits: ['update:modelValue']
}
</script>
在父组件中使用:
<template>
<ToggleSwitch v-model="isActive" />
</template>
<script>
import ToggleSwitch from './ToggleSwitch.vue'
export default {
components: { ToggleSwitch },
data() {
return {
isActive: false
}
}
}
</script>
使用 CSS 过渡动画增强效果
为 toggle 添加更流畅的动画效果可以通过 CSS transition 实现。
.toggle-animate {
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.toggle-animate:before {
transition: all 0.3s ease-in-out;
}
使用第三方库实现高级 Toggle
对于更复杂的需求,可以考虑使用第三方库如 vue-js-toggle-button:
安装:
npm install vue-js-toggle-button
使用:
<template>
<toggle-button
v-model="toggleValue"
:color="{checked: '#42b983', unchecked: '#ff0000'}"
:sync="true"
/>
</template>
<script>
import { ToggleButton } from 'vue-js-toggle-button'
export default {
components: {
ToggleButton
},
data() {
return {
toggleValue: false
}
}
}
</script>
无障碍访问优化
确保 toggle 控件对屏幕阅读器友好:
<label class="toggle">
<input
type="checkbox"
v-model="isActive"
aria-labelledby="toggle-label"
>
<span class="slider"></span>
<span id="toggle-label" class="sr-only">Toggle dark mode</span>
</label>
<style>
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
</style>






