效果:
<template>
<div class="slideSwitch">
<!-- switch存在与否取决于flag是否为true -->
<label role='checkbox' :class="['switch',{toggled}]">
<!--复选框,改变toggled的值 -->
<input type="checkbox" class="switch-input" @change="toggle">
<div class="switch-core" :style="{backgroundColor: toggled ? colorChecked: colorUnchecked}">
<div class="switch-button" :style="{transition:`transform ${speed}ms`,transform:toggled?null:`translate3d(32px, 0px, 0px)`}"></div>
</div>
</label>
</div>
</template>
<script>
export default {
name:'slideswitch',
props:{
value:{
type:Boolean,
default:true
},
speed:{
type:Number,
default:100
},
colorChecked:{
type:String,
default:'#5FDAC7'
},
colorUnchecked:{
type:String,
default:'#DFDFDF'
}
},
data(){
return{
toggled:this.value
}
},
watch:{
value:function(val){
this.value=val;
}
},
methods:{
toggle(event){
this.toggled=!this.toggled;
this.$emit('update:value',this.toggled);
this.$emit('change',event);
}
}
}
</script>
<style lang="less" scoped>
.switch {
display: inline-block;
position: relative;
overflow: hidden;
vertical-align: middle;
user-select: none;
font-size: 10px;
cursor: pointer;
.switch-input {
display: none;
}
.switch-label {
position: absolute;
top: 0;
font-weight: 600;
color: white;
z-index: 2;
}
.switch-core {
display: block;
position: relative;
box-sizing: border-box;
outline: 0;
margin: 0;
transition: border-color 0.3s, background-color 0.3s;
user-select: none;
width: 61px;
height: 27px;
border-radius: 16px;
// line-height: 20px;
.switch-button {
width: 23px;
height: 23px;
display: block;
position: absolute;
overflow: hidden;
top: 2;
left: 2;
z-index: 3;
transform: translate3d(0, 0, 0);
background-color: rgba(255, 255, 255, 1);
border-radius: 16px;
margin-top: 2px;
margin-left: 2px;
}
}
}
</style>
在需要的地方
<slideSwitch :value='value'></slideSwitch>