vue实现switch
Vue 实现 Switch 组件
在 Vue 中实现一个 Switch 开关组件可以通过自定义组件的方式完成。以下是两种常见的实现方法:
使用原生 HTML 和 CSS
通过 Vue 的模板和数据绑定实现基础的 Switch 功能:
<template>
<label class="switch">
<input type="checkbox" v-model="isChecked" @change="handleChange">
<span class="slider round"></span>
</label>
</template>
<script>
export default {
data() {
return {
isChecked: false
}
},
methods: {
handleChange() {
this.$emit('change', this.isChecked);
}
}
}
</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 库
大多数 Vue UI 框架都提供了现成的 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="value" color="primary"></v-switch>
</template>
<script>
export default {
data() {
return {
value: true
}
}
}
</script>
自定义 Switch 组件的高级功能
如果需要更复杂的功能,可以扩展基础组件:

<template>
<div class="custom-switch" :class="{ 'disabled': disabled }" @click="toggle">
<div class="switch-track" :class="{ 'active': modelValue }">
<div class="switch-thumb" :class="{ 'active': modelValue }"></div>
</div>
<span class="label">{{ label }}</span>
</div>
</template>
<script>
export default {
props: {
modelValue: Boolean,
label: String,
disabled: Boolean
},
methods: {
toggle() {
if (!this.disabled) {
this.$emit('update:modelValue', !this.modelValue);
}
}
}
}
</script>
<style>
.custom-switch {
display: flex;
align-items: center;
cursor: pointer;
}
.switch-track {
width: 50px;
height: 24px;
background-color: #ddd;
border-radius: 12px;
position: relative;
transition: background-color 0.3s;
}
.switch-track.active {
background-color: #4CAF50;
}
.switch-thumb {
width: 20px;
height: 20px;
background-color: white;
border-radius: 50%;
position: absolute;
top: 2px;
left: 2px;
transition: transform 0.3s;
}
.switch-thumb.active {
transform: translateX(26px);
}
.label {
margin-left: 8px;
}
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>
这些实现方法涵盖了从基础到高级的 Switch 组件需求,可以根据项目具体需求选择适合的方式。






