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"></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 Plus、Ant Design Vue 等已提供现成 Switch 组件:
Element Plus 示例

<template>
<el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949"/>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const value = ref(false)
return { value }
}
}
</script>
Ant Design Vue 示例
<template>
<a-switch v-model:checked="checked" />
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const checked = ref(false)
return { checked }
}
}
</script>
自定义事件扩展
原生实现时可添加 @change 事件处理:
<input
type="checkbox"
v-model="isChecked"
@change="handleSwitchChange"
>
methods: {
handleSwitchChange() {
console.log('当前状态:', this.isChecked)
this.$emit('change', this.isChecked)
}
}






