学习vue —— switch组件

/*
* @Author: dgh
* @Date: 2017-08-15 15:42:00
* @Last Modified by: dgh
* @Last Modified time: 2017-08-15 18:21:12
*/

<style lang="less">
@span-width: 62px;
@span-height: 30px;
@i-height: 24px;
@i-left: 26px;

.d-switch{
display: inline-block;
position: relative;
width: @span-width;
height: @span-height;
border-width: 1px;
border-style: solid;
border-radius: @span-height;
line-height: @span-height;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.switch-on{
position: absolute;
left: 6px;
}
.switch-off{
position: absolute;
right: 6px;
}
.d-switch i {
position: absolute;
top: 2px;
width: @i-height;
height: @i-height;
border-radius: @i-height;
background-color: #d2d2d2;
-webkit-transition: .1s linear;
transition: .1s linear;
}
.switch-on i {
left: @i-left;
background-color: #fff;
}
.switch-off i{
left: -@i-left;
}
.switch-on span, .switch-off span{
font-size:14px;
color: #fff;
}
</style>
<template>
<span :data-flag="flag" class="d-switch" role="switch" :style="activeStyle" @click="toggle">
<span class="switch-on" v-show="checked">
<i></i>
<span >{{onText}}</span>
</span>
<span class="switch-off" v-show="!checked">
<i></i>
<span>{{offText}}</span>
</span>
</span>
</template>

<script>
export default{
data(){
return{
onText: "ON",
offText: "OFF",
onColor: "#5FB878",
offColor: "#999999",
checked: true
}
},
computed: {
flag(){
return this.checked + '';
},
switchOn(){
return{
backgroundColor: this.onColor,
borderColor: this.onColor
}
},
switchOff(){
return{
backgroundColor: this.offColor,
borderColor: this.offColor
}
},
activeStyle(){
if(this.checked){
return this.switchOn;
}else{
return this.switchOff;
}
}
},
components:{

},
methods: {
toggle(){
this.checked = !this.checked;
}
}
}
</script>

posted @ 2017-08-16 23:38  忘忧人  阅读(2222)  评论(0编辑  收藏  举报