YZProjectCloud/yanzhu-ui-app/miniprogram/components/custom-stepper/index.js

119 lines
2.1 KiB
JavaScript

Component({
options: {
addGlobalClass: true,
},
properties: {
// 当前值
value: {
type: Number,
value: 0,
observer: function (newVal) {
this.setData({
currentValue: newVal
});
}
},
// 最小值
min: {
type: Number,
value: 0
},
// 最大值
max: {
type: Number,
value: 100
},
// 步长
step: {
type: Number,
value: 1
},
// 是否禁用
disabled: {
type: Boolean,
value: false
}
},
data: {
currentValue: 0
},
lifetimes: {
attached: function () {
this.setData({
currentValue: this.data.value
});
}
},
methods: {
// 减少值
onMinus: function () {
if (this.data.disabled) return;
const newValue = this.data.currentValue - this.data.step;
if (newValue >= this.data.min) {
this.updateValue(newValue);
}
},
// 增加值
onPlus: function () {
if (this.data.disabled) return;
const newValue = this.data.currentValue + this.data.step;
if (newValue <= this.data.max) {
this.updateValue(newValue);
}
},
// 输入框输入事件
onInput: function (e) {
if (this.data.disabled) return;
const value = parseFloat(e.detail.value);
if (!isNaN(value)) {
this.setData({
currentValue: value
});
}
},
// 输入框失去焦点事件
onBlur: function () {
if (this.data.disabled) return;
let value = this.data.currentValue;
// 限制范围
if (value < this.data.min) {
value = this.data.min;
} else if (value > this.data.max) {
value = this.data.max;
}
this.updateValue(value);
},
// 更新值
updateValue: function (value) {
// 保留两位小数
value = Math.round(value * 100) / 100;
this.setData({
currentValue: value
});
// 触发自定义事件
this.triggerEvent('change', {
value: value
});
}
}
});