u-number-box.vue 13 KB

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