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