<template>
<view
class="u-switch"
:class="[value == true ? 'u-switch--on' : '', disabled ? 'u-switch--disabled' : '']"
@tap="onClick"
:style="[switchStyle]"
>
<view class="u-switch__node node-class">
<u-loading
:show="loading"
class="u-switch__loading"
:size="size * 0.6"
:color="loadingColor"
/>
</view>
</view>
</template>
<script>
export default {
name: 'u-switch',
props: {
loading: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
size: {
type: [Number, String],
default: 25
},
activeColor: {
type: String,
default: '#2979ff'
},
inactiveColor: {
type: String,
default: '#ffffff'
},
value: {
type: Boolean,
default: false
},
vibrateShort: {
type: Boolean,
default: false
},
activeValue: {
type: [Number, String, Boolean],
default: true
},
inactiveValue: {
type: [Number, String, Boolean],
default: false
}
},
data() {
return {}
},
computed: {
switchStyle() {
let style = {}
style.fontSize = this.size + 'rpx'
style.backgroundColor = this.value ? this.activeColor : this.inactiveColor
return style
},
loadingColor() {
return this.value ? this.activeColor : null
}
},
methods: {
onClick() {
if (!this.disabled && !this.loading) {
if (this.vibrateShort) uni.vibrateShort()
this.$emit('input', !this.value)
this.$nextTick(() => {
this.$emit(
'change',
this.value ? this.activeValue : this.inactiveValue
)
})
}
}
}
}
</script>
<style lang="scss" scoped>
@import '../../libs/css/style.components.scss';
.u-switch {
position: relative;
display: inline-block;
box-sizing: initial;
width: 2em;
height: 1em;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 1em;
transition: background-color 0.3s;
font-size: 25rpx;
}
.u-switch__node {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
border-radius: 100%;
z-index: 1;
width: 1em;
height: 1em;
background-color: #fff;
background-color: #fff;
box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1),
0 3px 3px 0 rgba(0, 0, 0, 0.05);
box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1),
0 3px 3px 0 rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05),
-webkit-transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
transition: transform cubic-bezier(0.3, 1.05, 0.4, 1.05);
transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
}
.u-switch__loading {
display: flex;
align-items: center;
justify-content: center;
}
.u-switch--on {
background-color: #1989fa;
}
.u-switch--on .u-switch__node {
transform: translateX(1em);
}
.u-switch--disabled {
opacity: 0.4;
}
</style>