vue自定义switch开关,使用less支持换肤

2022-10-21,,,,

实际项目用到了,记录一下,也方便以后使用,这样也可以避免为了使用一个switch,引入整个外部web框架;

也可以方便更好的理解是和使用less。

基础代码使用的是网上的,然后自己添加了less换肤,修改了样式。

代码如下:

<template>
<div :class="{'theme-danger':danger,'theme-default':!danger}">
<span class="weui-switch" :class="{'weui-switch-on' : isChecked}" :value="value" @click="toggle"
style="position:relative">
<div v-if="isChecked && direction.length > 0"
style="width:100%;height:100%;position:absolute;padding:0 5px;line-height:20px;color:#FFF;user-select:none">
{{direction[0]}}
</div> <div v-if="!isChecked && direction.length > 0"
style="width:100%;height:100%;position:absolute;padding:0 5px;right:2px;line-height:22px;color:#7A7A7A;text-align:right;user-select:none">
{{direction[1]}}
</div> </span>
</div>
</template> <script>
export default {
name: 'switchComponent',
props: {
value: {
type: Boolean,
default: true
},
//开关文字描述
text: {
type: String,
default: ''
},
//目前定义的一个主题,支持后续自己替换
danger: {
type: Boolean,
default: false
},
},
data() {
return {
isChecked: this.value
}
},
computed: {
direction() {
if (this.text) {
return this.text.split('|')
} else {
return []
}
}
},
watch: {
value(val) {
this.isChecked = val
},
isChecked(val) {
this.$emit('change', val);
}
},
methods: {
toggle() {
this.isChecked = !this.isChecked;
}
}
}
</script> <style scoped lang="less"> /* 公共函数部分 */
.theme(@default-color,@border-color) {
/*将所有的涉及到切换主题的样式全部放在此处*/
.weui-switch {
display: block;
position: relative;
width: 38px;
height: 20px;
border: 1px @border-color;
outline: 0;
border-radius: 15px;
box-sizing: border-box;
background-color: @border-color;
transition: background-color 0.1s, border 0.1s;
cursor: pointer;
box-shadow: 0 1px 1px @default-color;
} .weui-switch:before {
content: " ";
position: absolute;
top: 1px;
left: 1px;
width: 36px;
height: 19px;
border-radius: 15px;
background: rgba(18, 39, 66);
transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1);
} .weui-switch:after {
content: " ";
position: absolute;
top: 3px;
left: 3px;
width: 15px;
height: 15px;
border-radius: 10px;
background-color: @default-color;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
} .weui-switch-on:after {
background: #FFFFFF;
} .weui-switch-on {
border-color: #6F6F6F;
background-color: @default-color;
} .weui-switch-on:before {
border-color: @border-color;
background-color: @default-color;
} .weui-switch-on:after {
transform: translateX(17px);
}
} /*不同主题传不同的变量*/
.theme-default {
@default-color: rgba(34, 190, 255, 1);
@border-color: rgba(34, 190, 255, 1);
.theme(@default-color, @border-color);
} .theme-danger {
@default-color: rgba(235, 97, 0, 1);
@border-color: #EB6100;
.theme(@default-color, @border-color);
} </style>

vue自定义switch开关,使用less支持换肤的相关教程结束。

《vue自定义switch开关,使用less支持换肤.doc》

下载本文的Word格式文档,以方便收藏与打印。