index.vue 14 KB

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