blob: 54a679eb5b0b5f75b6b00fcfe29d73507a7dd0ca [file] [log] [blame]
guangchao.xu070005a2020-12-07 09:56:40 +08001<template>
2 <view class="u-numberbox">
3 <view class="u-icon-minus" @touchstart.stop.prevent="btnTouchStart('minus')" @touchend.stop.prevent="clearTimer" :class="{ 'u-icon-disabled': disabled || inputVal <= min }"
4 :style="{
5 background: bgColor,
6 height: inputHeight + 'rpx',
7 color: color
8 }">
9 <u-icon name="minus" :size="size"></u-icon>
10 </view>
11 <input :disabled="disabledInput || disabled" :cursor-spacing="getCursorSpacing" :class="{ 'u-input-disabled': disabled }"
12 v-model="inputVal" class="u-number-input" @blur="onBlur" @focus="onFocus"
13 type="number" :style="{
14 color: color,
15 fontSize: size + 'rpx',
16 background: bgColor,
17 height: inputHeight + 'rpx',
18 width: inputWidth + 'rpx'
19 }" />
20 <view class="u-icon-plus" @touchstart.stop.prevent="btnTouchStart('plus')" @touchend.stop.prevent="clearTimer" :class="{ 'u-icon-disabled': disabled || inputVal >= max }"
21 :style="{
22 background: bgColor,
23 height: inputHeight + 'rpx',
24 color: color
25 }">
26 <u-icon name="plus" :size="size"></u-icon>
27 </view>
28 </view>
29</template>
30
31<script>
32 /**
33 * numberBox 步进器
34 * @description 该组件一般用于商城购物选择物品数量的场景。注意:该输入框只能输入大于或等于0的整数,不支持小数输入
35 * @tutorial https://www.uviewui.com/components/numberBox.html
36 * @property {Number} value 输入框初始值(默认1)
37 * @property {String} bg-color 输入框和按钮的背景颜色(默认#F2F3F5)
38 * @property {Number} min 用户可输入的最小值(默认0)
39 * @property {Number} max 用户可输入的最大值(默认99999)
40 * @property {Number} step 步长,每次加或减的值(默认1)
41 * @property {Boolean} disabled 是否禁用操作,禁用后无法加减或手动修改输入框的值(默认false)
42 * @property {Boolean} disabled-input 是否禁止输入框手动输入值(默认false)
43 * @property {Boolean} positive-integer 是否只能输入正整数(默认true)
44 * @property {String | Number} size 输入框文字和按钮字体大小,单位rpx(默认26)
45 * @property {String} color 输入框文字和加减按钮图标的颜色(默认#323233)
46 * @property {String | Number} input-width 输入框宽度,单位rpx(默认80)
47 * @property {String | Number} input-height 输入框和按钮的高度,单位rpx(默认50)
48 * @property {String | Number} index 事件回调时用以区分当前发生变化的是哪个输入框
49 * @property {Boolean} long-press 是否开启长按连续递增或递减(默认true)
50 * @property {String | Number} press-time 开启长按触发后,每触发一次需要多久,单位ms(默认250)
51 * @property {String | Number} cursor-spacing 指定光标于键盘的距离,避免键盘遮挡输入框,单位rpx(默认200)
52 * @event {Function} change 输入框内容发生变化时触发,对象形式
53 * @event {Function} blur 输入框失去焦点时触发,对象形式
54 * @event {Function} minus 点击减少按钮时触发(按钮可点击情况下),对象形式
55 * @event {Function} plus 点击增加按钮时触发(按钮可点击情况下),对象形式
56 * @example <u-number-box :min="1" :max="100"></u-number-box>
57 */
58 export default {
59 name: "u-number-box",
60 props: {
61 // 预显示的数字
62 value: {
63 type: Number,
64 default: 1
65 },
66 // 背景颜色
67 bgColor: {
68 type: String,
69 default: '#F2F3F5'
70 },
71 // 最小值
72 min: {
73 type: Number,
74 default: 0
75 },
76 // 最大值
77 max: {
78 type: Number,
79 default: 99999
80 },
81 // 步进值,每次加或减的值
82 step: {
83 type: Number,
84 default: 1
85 },
86 // 是否禁用加减操作
87 disabled: {
88 type: Boolean,
89 default: false
90 },
91 // input的字体大小,单位rpx
92 size: {
93 type: [Number, String],
94 default: 26
95 },
96 // 加减图标的颜色
97 color: {
98 type: String,
99 default: '#323233'
100 },
101 // input宽度,单位rpx
102 inputWidth: {
103 type: [Number, String],
104 default: 80
105 },
106 // input高度,单位rpx
107 inputHeight: {
108 type: [Number, String],
109 default: 50
110 },
111 // index索引,用于列表中使用,让用户知道是哪个numberbox发生了变化,一般使用for循环出来的index值即可
112 index: {
113 type: [Number, String],
114 default: ''
115 },
116 // 是否禁用输入框,与disabled作用于输入框时,为OR的关系,即想要禁用输入框,又可以加减的话
117 // 设置disabled为false,disabledInput为true即可
118 disabledInput: {
119 type: Boolean,
120 default: false
121 },
122 // 输入框于键盘之间的距离
123 cursorSpacing: {
124 type: [Number, String],
125 default: 100
126 },
127 // 是否开启长按连续递增或递减
128 longPress: {
129 type: Boolean,
130 default: true
131 },
132 // 开启长按触发后,每触发一次需要多久
133 pressTime: {
134 type: [Number, String],
135 default: 250
136 },
137 // 是否只能输入大于或等于0的整数(正整数)
138 positiveInteger: {
139 type: Boolean,
140 default: true
141 }
142 },
143 watch: {
144 value(v1, v2) {
145 // 只有value的改变是来自外部的时候,才去同步inputVal的值,否则会造成循环错误
146 if(!this.changeFromInner) {
147 this.inputVal = v1;
148 // 因为inputVal变化后,会触发this.handleChange(),在其中changeFromInner会再次被设置为true,
149 // 造成外面修改值,也导致被认为是内部修改的混乱,这里进行this.$nextTick延时,保证在运行周期的最后处
150 // 将changeFromInner设置为false
151 this.$nextTick(function(){
152 this.changeFromInner = false;
153 })
154 }
155 },
156 inputVal(v1, v2) {
157 // 为了让用户能够删除所有输入值,重新输入内容,删除所有值后,内容为空字符串
158 if (v1 == '') return;
159 let value = 0;
160 // 首先判断是否数值,并且在min和max之间,如果不是,使用原来值
161 let tmp = this.$u.test.number(v1);
162 if (tmp && v1 >= this.min && v1 <= this.max) value = v1;
163 else value = v2;
164 // 判断是否只能输入大于等于0的整数
165 if(this.positiveInteger) {
166 // 小于0,或者带有小数点,
167 if(v1 < 0 || String(v1).indexOf('.') !== -1) {
168 value = v2;
169 // 双向绑定input的值,必须要使用$nextTick修改显示的值
170 this.$nextTick(() => {
171 this.inputVal = v2;
172 })
173 }
174 }
175 // 发出change事件
176 this.handleChange(value, 'change');
177 }
178 },
179 data() {
180 return {
181 inputVal: 1, // 输入框中的值,不能直接使用props中的value,因为应该改变props的状态
182 timer: null, // 用作长按的定时器
183 changeFromInner: false, // 值发生变化,是来自内部还是外部
184 innerChangeTimer: null, // 内部定时器
185 };
186 },
187 created() {
188 this.inputVal = Number(this.value);
189 },
190 computed: {
191 getCursorSpacing() {
192 // 先将值转为px单位,再转为数值
193 return Number(uni.upx2px(this.cursorSpacing));
194 }
195 },
196 methods: {
197 // 点击退格键
198 btnTouchStart(callback) {
199 // 先执行一遍方法,否则会造成松开手时,就执行了clearTimer,导致无法实现功能
200 this[callback]();
201 // 如果没开启长按功能,直接返回
202 if (!this.longPress) return;
203 clearInterval(this.timer); //再次清空定时器,防止重复注册定时器
204 this.timer = null;
205 this.timer = setInterval(() => {
206 // 执行加或减函数
207 this[callback]();
208 }, this.pressTime);
209 },
210 clearTimer() {
211 this.$nextTick(() => {
212 clearInterval(this.timer);
213 this.timer = null;
214 })
215 },
216 minus() {
217 this.computeVal('minus');
218 },
219 plus() {
220 this.computeVal('plus');
221 },
222 // 为了保证小数相加减出现精度溢出的问题
223 calcPlus(num1, num2) {
224 let baseNum, baseNum1, baseNum2;
225 try {
226 baseNum1 = num1.toString().split('.')[1].length;
227 } catch (e) {
228 baseNum1 = 0;
229 }
230 try {
231 baseNum2 = num2.toString().split('.')[1].length;
232 } catch (e) {
233 baseNum2 = 0;
234 }
235 baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
236 let precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2; //精度
237 return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision);
238 },
239 // 为了保证小数相加减出现精度溢出的问题
240 calcMinus(num1, num2) {
241 let baseNum, baseNum1, baseNum2;
242 try {
243 baseNum1 = num1.toString().split('.')[1].length;
244 } catch (e) {
245 baseNum1 = 0;
246 }
247 try {
248 baseNum2 = num2.toString().split('.')[1].length;
249 } catch (e) {
250 baseNum2 = 0;
251 }
252 baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
253 let precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2;
254 return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
255 },
256 computeVal(type) {
257 uni.hideKeyboard();
258 if (this.disabled) return;
259 let value = 0;
260 // 减
261 if (type === 'minus') {
262 value = this.calcMinus(this.inputVal, this.step);
263 } else if (type === 'plus') {
264 value = this.calcPlus(this.inputVal, this.step);
265 }
266 // 判断是否小于最小值和大于最大值
267 if (value < this.min || value > this.max) {
268 return;
269 }
270 this.inputVal = value;
271 this.handleChange(value, type);
272 },
273 // 处理用户手动输入的情况
274 onBlur(event) {
275 let val = 0;
276 let value = event.detail.value;
277 // 如果为非0-9数字组成,或者其第一位数值为0,直接让其等于min值
278 // 这里不直接判断是否正整数,是因为用户传递的props min值可能为0
279 if (!/(^\d+$)/.test(value) || value[0] == 0) val = this.min;
280 val = +value;
281 if (val > this.max) {
282 val = this.max;
283 } else if (val < this.min) {
284 val = this.min;
285 }
286 this.$nextTick(() => {
287 this.inputVal = val;
288 })
289 this.handleChange(val, 'blur');
290 },
291 // 输入框获得焦点事件
292 onFocus() {
293 this.$emit('focus');
294 },
295 handleChange(value, type) {
296 if (this.disabled) return;
297 // 清除定时器,避免造成混乱
298 if(this.innerChangeTimer) {
299 clearTimeout(this.innerChangeTimer);
300 this.innerChangeTimer = null;
301 }
302 // 发出input事件,修改通过v-model绑定的值,达到双向绑定的效果
303 this.changeFromInner = true;
304 // 一定时间内,清除changeFromInner标记,否则内部值改变后
305 // 外部通过程序修改value值,将会无效
306 this.innerChangeTimer = setTimeout(() => {
307 this.changeFromInner = false;
308 }, 150);
309 this.$emit('input', Number(value));
310 this.$emit(type, {
311 // 转为Number类型
312 value: Number(value),
313 index: this.index
314 })
315 }
316 }
317 };
318</script>
319
320<style lang="scss" scoped>
321 @import "../../libs/css/style.components.scss";
322
323 .u-numberbox {
324 display: inline-flex;
325 align-items: center;
326 }
327
328 .u-number-input {
329 position: relative;
330 text-align: center;
331 padding: 0;
332 margin: 0 6rpx;
333 @include vue-flex;
334 align-items: center;
335 justify-content: center;
336 }
337
338 .u-icon-plus,
339 .u-icon-minus {
340 width: 60rpx;
341 @include vue-flex;
342 justify-content: center;
343 align-items: center;
344 }
345
346 .u-icon-plus {
347 border-radius: 0 8rpx 8rpx 0;
348 }
349
350 .u-icon-minus {
351 border-radius: 8rpx 0 0 8rpx;
352 }
353
354 .u-icon-disabled {
355 color: #c8c9cc !important;
356 background: #f7f8fa !important;
357 }
358
359 .u-input-disabled {
360 color: #c8c9cc !important;
361 background-color: #f2f3f5 !important;
362 }
363</style>