[fix] 修复switch组件交互模式,严格遵守mvvm思想,直接使用v-model绑定值后,切换按钮直接改绑定的值,不再需要@change里面去获取,简化了开发工作量

This commit is contained in:
aisen
2026-01-28 10:23:14 +08:00
parent 5b1e863066
commit d355989fcf

View File

@@ -2,7 +2,7 @@
<view <view
class="tn-switch-class tn-switch" class="tn-switch-class tn-switch"
:class="[ :class="[
value ? 'tn-switch--on' : '', switchState ? 'tn-switch--on' : '',
disabled ? 'tn-switch--disabled' : '', disabled ? 'tn-switch--disabled' : '',
`tn-switch--${shape}` `tn-switch--${shape}`
]" ]"
@@ -22,7 +22,7 @@
class="tn-switch__icon tn-switch__icon--left" class="tn-switch__icon tn-switch__icon--left"
:class="[ :class="[
`tn-icon-${leftIcon}`, `tn-icon-${leftIcon}`,
value ? 'tn-switch__icon--show' : '' switchState ? 'tn-switch__icon--show' : ''
]" ]"
:style="[iconStyle]"></view> :style="[iconStyle]"></view>
<!-- 右图标 --> <!-- 右图标 -->
@@ -31,7 +31,7 @@
class="tn-switch__icon tn-switch__icon--right" class="tn-switch__icon tn-switch__icon--right"
:class="[ :class="[
`tn-icon-${rightIcon}`, `tn-icon-${rightIcon}`,
!value ? 'tn-switch__icon--show' : '' !switchState ? 'tn-switch__icon--show' : ''
]" ]"
:style="[iconStyle]"></view> :style="[iconStyle]"></view>
</view> </view>
@@ -42,7 +42,7 @@
name: 'tn-switch', name: 'tn-switch',
props: { props: {
value: { value: {
type: Boolean, type: [Number, String, Boolean],
default: false default: false
}, },
// 按钮的样式 // 按钮的样式
@@ -106,7 +106,7 @@
switchStyle() { switchStyle() {
let style = {} let style = {}
style.fontSize = this.$tn.string.getLengthUnitValue(this.size) style.fontSize = this.$tn.string.getLengthUnitValue(this.size)
style.backgroundColor = this.value ? style.backgroundColor = this.switchState ?
this.activeColor ? this.activeColor : '#01BEFF' : this.activeColor ? this.activeColor : '#01BEFF' :
this.inactiveColor ? this.inactiveColor : '#AAAAAA' this.inactiveColor ? this.inactiveColor : '#AAAAAA'
return style return style
@@ -124,22 +124,33 @@
return style return style
}, },
loadingColor() { loadingColor() {
return this.value ? this.activeColor : '' return this.switchState ? this.activeColor : ''
}
},
watch:{
value:{
handler(newVal,oldVal){
this.switchState = (this.value == this.activeValue);
}
} }
}, },
data() { data() {
return { return {
switchState:false
} }
}, },
mounted() {
this.switchState = (this.value == this.activeValue);
},
methods: { methods: {
click() { click() {
this.switchState = !this.switchState;
if (!this.disabled && !this.loading) { if (!this.disabled && !this.loading) {
if (this.vibrateShort) uni.vibrateShort() if (this.vibrateShort) uni.vibrateShort()
this.$emit('input', !this.value) this.$emit('input', this.switchState ? this.activeValue : this.inactiveValue)
// 放到下一个生命周期因为双向绑定的value修改父组件状态需要时间且是异步的 // 放到下一个生命周期因为双向绑定的value修改父组件状态需要时间且是异步的
this.$nextTick(() => { this.$nextTick(() => {
this.$emit('change', this.value ? this.activeValue : this.inactiveValue); this.$emit('change', this.switchState ? this.activeValue : this.inactiveValue);
}) })
} }
} }