vue实现switch开关
Vue 实现 Switch 开关
使用原生 HTML 和 CSS
可以通过原生的 HTML 复选框结合 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>
使用第三方组件库
Vue 生态中有许多成熟的 UI 组件库提供了 Switch 开关组件,可以直接使用。
Element UI
<template>
<el-switch v-model="isChecked"></el-switch>
</template>
<script>
export default {
data() {
return {
isChecked: false
}
}
}
</script>
Ant Design Vue
<template>
<a-switch v-model:checked="isChecked" />
</template>
<script>
export default {
data() {
return {
isChecked: false
}
}
}
</script>
自定义 Switch 组件
可以封装一个可复用的 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"></span>
</label>
</template>
<script>
export default {
name: 'CustomSwitch',
props: {
modelValue: {
type: Boolean,
default: false
}
}
}
</script>
<style>
.custom-switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.custom-switch input {
opacity: 0;
width: 0;
height: 0;
}
.custom-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 24px;
}
.custom-slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .custom-slider {
background-color: #42b983;
}
input:checked + .custom-slider:before {
transform: translateX(26px);
}
</style>
使用自定义组件
<template>
<CustomSwitch v-model="isActive" />
</template>
<script>
import CustomSwitch from './Switch.vue'
export default {
components: {
CustomSwitch
},
data() {
return {
isActive: false
}
}
}
</script>
以上方法可以根据项目需求选择适合的方式实现 Switch 开关功能。







