// 赶进度待优化 Component({ properties: { value: { type: null, value: 0, observer() { this.updated() } }, //最小数值 min: { type: Number, value: -999999 }, //最大数值 max: { type: Number, value: 999999, observer() { this.updated() } }, //递增或递减步长 step: { type: Number, value: 1 }, //是否禁用 disabled: { type: Boolean, value: false }, //是否禁用输入 disabledInput: { type: Boolean, value: false }, //是否整数 integer: { type: Boolean, value: false } }, data: { disabledMinus: false, disabledAdd: false }, methods: { //数据更新 updated() { const val = this.data.value if (val == '' || isNaN(val)) return if (val <= this.data.min) { this.setData({ disabledMinus: true, value: this.data.min }) } else { this.setData({ disabledMinus: false }) } if (val >= this.data.max) { this.setData({ disabledAdd: true, value: this.data.max }) } else { this.setData({ disabledAdd: false }) } }, //实时监听input输入 inputChange(e: WechatMiniprogram.Input) { this.setData({ value: e.detail.value }) }, //计算精度 fixedFloat(a: number, b: number, sign: string) { const handle = (x: number): [string, number] => { let y = String(x) let p = y.lastIndexOf('.') if (p === -1) { return [y, 0] } else { return [y.replace('.', ''), y.length - p - 1] } } // v 操作数1, w 操作数2, s 操作符, t 精度 const operate = (v: number, w: number, s: string, t: number) => { switch (s) { case '+': return (v + w) / t case '-': return (v - w) / t case '*': return (v * w) / (t * t) case '/': return (v / w) default: return 0 } } const padding0 = (p: number) => { var z = '' while (p--) { z += '0' } return z } const c: [string, number] = handle(a) const d: [string, number] = handle(b) let k = 0 if (c[1] === 0 && d[1] === 0) { return operate(+c[0], +d[0], sign, 1) } else { k = Math.pow(10, Math.max(c[1], d[1])) if (c[1] !== d[1]) { if (c[1] > d[1]) { d[0] += padding0(c[1] - d[1]) } else { c[0] += padding0(d[1] - c[1]) } } return operate(+c[0], +d[0], sign, k) } }, minus() { this.setData({ value: this.fixedFloat(this.data.value, this.data.step, '-') }, () => { this.triggerEvent('change', this.data.value) }) }, add() { this.setData({ value: this.fixedFloat(this.data.value, this.data.step, '+') }, () => { this.triggerEvent('change', this.data.value) }) }, //失去焦点 inputBlur() { if (this.data.value === '' || isNaN(this.data.value)) { if (this.data.min > 0) { this.setData({ value: this.data.min }) } else { this.setData({ value: this.data.max < 0 ? this.data.max : 0 }) } } else { if (this.data.integer) { this.setData({ value: parseInt(this.data.value) }) } } this.triggerEvent('change', this.data.value) } } })