u-number-box.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <template>
  2. <view class="u-number-box">
  3. <view
  4. class="u-number-box__slot"
  5. @tap.stop="clickHandler('minus')"
  6. @touchstart="onTouchStart('minus')"
  7. @touchend.stop="clearTimeout"
  8. v-if="showMinus && $slots.minus"
  9. >
  10. <slot name="minus" />
  11. </view>
  12. <view
  13. v-else-if="showMinus"
  14. class="u-number-box__minus"
  15. @tap.stop="clickHandler('minus')"
  16. @touchstart="onTouchStart('minus')"
  17. @touchend.stop="clearTimeout"
  18. hover-class="u-number-box__minus--hover"
  19. hover-stay-time="150"
  20. :class="{ 'u-number-box__minus--disabled': isDisabled('minus') }"
  21. :style="[buttonStyle('minus')]"
  22. >
  23. <u-icon
  24. name="minus"
  25. :color="isDisabled('minus') ? disableColor : color"
  26. :size="iconSize"
  27. :customStyle="iconStyle"
  28. ></u-icon>
  29. </view>
  30. <slot name="input">
  31. <input
  32. :disabled="disabledInput || disabled"
  33. :cursor-spacing="getCursorSpacing"
  34. :class="{ 'u-number-box__input--disabled': disabled || disabledInput }"
  35. v-model="currentValue"
  36. class="u-number-box__input"
  37. @blur="onBlur"
  38. @focus="onFocus"
  39. @input="onInput"
  40. :type="integer ? 'number' : 'digit'"
  41. :style="[inputStyle]"
  42. />
  43. </slot>
  44. <view
  45. class="u-number-box__slot"
  46. @tap.stop="clickHandler('plus')"
  47. @touchstart="onTouchStart('plus')"
  48. @touchend.stop="clearTimeout"
  49. v-if="showPlus && $slots.plus"
  50. >
  51. <slot name="plus" />
  52. </view>
  53. <view
  54. v-else-if="showPlus"
  55. class="u-number-box__plus"
  56. @tap.stop="clickHandler('plus')"
  57. @touchstart="onTouchStart('plus')"
  58. @touchend.stop="clearTimeout"
  59. hover-class="u-number-box__plus--hover"
  60. hover-stay-time="150"
  61. :class="{ 'u-number-box__minus--disabled': isDisabled('plus') }"
  62. :style="[buttonStyle('plus')]"
  63. >
  64. <u-icon
  65. name="plus"
  66. :color="isDisabled('plus') ? disableColor : color"
  67. :size="iconSize"
  68. :customStyle="iconStyle"
  69. ></u-icon>
  70. </view>
  71. </view>
  72. </template>
  73. <script>
  74. import props from './props.js';
  75. import mixin from '../../libs/mixin/mixin'
  76. import mpMixin from '../../libs/mixin/mpMixin';
  77. /**
  78. * numberBox 步进器
  79. * @description 该组件一般用于商城购物选择物品数量的场景。
  80. * @tutorial https://uviewui.com/components/numberBox.html
  81. * @property {String | Number} name 步进器标识符,在change回调返回
  82. * @property {String | Number} value 用于双向绑定的值,初始化时设置设为默认min值(最小值) (默认 0 )
  83. * @property {String | Number} min 最小值 (默认 1 )
  84. * @property {String | Number} max 最大值 (默认 Number.MAX_SAFE_INTEGER )
  85. * @property {String | Number} step 加减的步长,可为小数 (默认 1 )
  86. * @property {Boolean} integer 是否只允许输入整数 (默认 false )
  87. * @property {Boolean} disabled 是否禁用,包括输入框,加减按钮 (默认 false )
  88. * @property {Boolean} disabledInput 是否禁用输入框 (默认 false )
  89. * @property {Boolean} asyncChange 是否开启异步变更,开启后需要手动控制输入值 (默认 false )
  90. * @property {String | Number} inputWidth 输入框宽度,单位为px (默认 35 )
  91. * @property {Boolean} showMinus 是否显示减少按钮 (默认 true )
  92. * @property {Boolean} showPlus 是否显示增加按钮 (默认 true )
  93. * @property {String | Number} decimalLength 显示的小数位数
  94. * @property {Boolean} longPress 是否开启长按加减手势 (默认 true )
  95. * @property {String} color 输入框文字和加减按钮图标的颜色 (默认 '#323233' )
  96. * @property {String | Number} buttonSize 按钮大小,宽高等于此值,单位px,输入框高度和此值保持一致 (默认 30 )
  97. * @property {String} bgColor 输入框和按钮的背景颜色 (默认 '#EBECEE' )
  98. * @property {String | Number} cursorSpacing 指定光标于键盘的距离,避免键盘遮挡输入框,单位px (默认 100 )
  99. * @property {Boolean} disablePlus 是否禁用增加按钮 (默认 false )
  100. * @property {Boolean} disableMinus 是否禁用减少按钮 (默认 false )
  101. * @property {Object | String} iconStyle 加减按钮图标的样式
  102. * @property {String} inputBgColor 输入框背景颜色 (默认 '#EBECEE' )
  103. * @property {String | Number} buttonRound 加减按钮圆角,单位px (默认 0 )
  104. * @property {String | Number} iconSize 加减按钮图标大小,单位px (默认 15 )
  105. *
  106. * @event {Function} onFocus 输入框活动焦点
  107. * @event {Function} onBlur 输入框失去焦点
  108. * @event {Function} onInput 输入框值发生变化
  109. * @event {Function} onChange
  110. * @example <u-number-box v-model="value" @change="valChange"></u-number-box>
  111. */
  112. export default {
  113. name: 'u-number-box',
  114. mixins: [mpMixin, mixin, props],
  115. data() {
  116. return {
  117. // 输入框实际操作的值
  118. currentValue: '',
  119. // 定时器
  120. longPressTimer: null
  121. }
  122. },
  123. watch: {
  124. // 多个值之间,只要一个值发生变化,都要重新检查check()函数
  125. watchChange(n) {
  126. this.check()
  127. },
  128. // 监听v-mode的变化,重新初始化内部的值
  129. // #ifdef VUE2
  130. value(n) {
  131. if (n !== this.currentValue) {
  132. this.currentValue = this.format(this.value)
  133. }
  134. },
  135. // #endif
  136. // #ifdef VUE3
  137. modelValue: {
  138. immediate: true,
  139. handler(newVal, oldVal) {
  140. if (newVal !== this.currentValue) {
  141. this.currentValue = this.format(this.modelValue)
  142. }
  143. }
  144. },
  145. // #endif
  146. },
  147. computed: {
  148. getCursorSpacing() {
  149. // 判断传入的单位,如果为px单位,需要转成px
  150. return uni.$u.getPx(this.cursorSpacing)
  151. },
  152. // 按钮的样式
  153. buttonStyle() {
  154. return (type) => {
  155. const style = {
  156. backgroundColor: this.bgColor,
  157. height: uni.$u.addUnit(this.buttonSize),
  158. width: uni.$u.addUnit(this.buttonSize),
  159. borderRadius: uni.$u.addUnit(this.buttonRound),
  160. color: this.color
  161. }
  162. if (this.isDisabled(type)) {
  163. style.color = this.disableColor
  164. style.backgroundColor = this.disableBgColor
  165. }
  166. return style
  167. }
  168. },
  169. // 输入框的样式
  170. inputStyle() {
  171. const style = {
  172. color: this.color,
  173. backgroundColor: this.inputBgColor || this.bgColor,
  174. height: uni.$u.addUnit(this.buttonSize),
  175. width: uni.$u.addUnit(this.inputWidth)
  176. }
  177. if(this.disabled){
  178. style.color = this.disableColor
  179. style.backgroundColor = this.disableBgColor
  180. }
  181. return style
  182. },
  183. // 用于监听多个值发生变化
  184. watchChange() {
  185. return [this.integer, this.decimalLength, this.min, this.max]
  186. },
  187. isDisabled() {
  188. return (type) => {
  189. if (type === 'plus') {
  190. // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  191. return (
  192. this.disabled ||
  193. this.disablePlus ||
  194. this.currentValue >= this.max
  195. )
  196. }
  197. // 点击减少按钮同理
  198. return (
  199. this.disabled ||
  200. this.disableMinus ||
  201. this.currentValue <= this.min
  202. )
  203. }
  204. },
  205. },
  206. mounted() {
  207. this.init()
  208. },
  209. // #ifdef VUE3
  210. emits: ['update:modelValue', 'focus', 'blur', 'change', 'plus', 'minus','overlimit'],
  211. // #endif
  212. methods: {
  213. init() {
  214. // #ifdef VUE2
  215. this.currentValue = this.format(this.value)
  216. // #endif
  217. // #ifdef VUE3
  218. this.currentValue = this.format(this.modelValue)
  219. // #endif
  220. },
  221. // 格式化整理数据,限制范围
  222. format(value) {
  223. value = this.filter(value)
  224. // 如果为空字符串,那么设置为0,同时将值转为Number类型
  225. value = value === '' ? 0 : +value
  226. // 对比最大最小值,取在min和max之间的值
  227. value = Math.max(Math.min(this.max, value), this.min)
  228. // 如果设定了最大的小数位数,使用toFixed去进行格式化
  229. if (this.decimalLength !== null) {
  230. value = value.toFixed(this.decimalLength)
  231. }
  232. return value
  233. },
  234. // 过滤非法的字符
  235. filter(value) {
  236. // 只允许0-9之间的数字,"."为小数点,"-"为负数时候使用
  237. value = String(value).replace(/[^0-9.-]/g, '')
  238. // 如果只允许输入整数,则过滤掉小数点后的部分
  239. if (this.integer && value.indexOf('.') !== -1) {
  240. value = value.split('.')[0]
  241. }
  242. return value;
  243. },
  244. check() {
  245. // 格式化了之后,如果前后的值不相等,那么设置为格式化后的值
  246. const val = this.format(this.currentValue);
  247. if (val !== this.currentValue) {
  248. this.currentValue = val
  249. }
  250. },
  251. // 判断是否出于禁止操作状态
  252. // isDisabled(type) {
  253. // if (type === 'plus') {
  254. // // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  255. // return (
  256. // this.disabled ||
  257. // this.disablePlus ||
  258. // this.currentValue >= this.max
  259. // )
  260. // }
  261. // // 点击减少按钮同理
  262. // return (
  263. // this.disabled ||
  264. // this.disableMinus ||
  265. // this.currentValue <= this.min
  266. // )
  267. // },
  268. // 输入框活动焦点
  269. onFocus(event) {
  270. this.$emit('focus', {
  271. ...event.detail,
  272. name: this.name,
  273. })
  274. },
  275. // 输入框失去焦点
  276. onBlur(event) {
  277. // 对输入值进行格式化
  278. //detail
  279. const value = this.format(event.target.value)
  280. if(value !== this.currentValue){
  281. //如果输入的值为空需要将值修改为最小值
  282. if(this.currentValue === ''){
  283. this.currentValue = value;
  284. }
  285. this.emitChange(value);
  286. }
  287. // 发出blur事件
  288. this.$emit(
  289. 'blur',{
  290. ...event.target,
  291. name: this.name,
  292. }
  293. )
  294. },
  295. // 输入框值发生变化
  296. onInput(e) {
  297. const {
  298. value = ''
  299. } = e.detail || {}
  300. // 为空返回
  301. if (value === '') return
  302. let formatted = this.filter(value)
  303. // 最大允许的小数长度
  304. if (this.decimalLength !== null && formatted.indexOf('.') !== -1) {
  305. const pair = formatted.split('.');
  306. formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`
  307. }
  308. formatted = this.format(formatted)
  309. this.emitChange(formatted);
  310. },
  311. // 发出change事件
  312. emitChange(value) {
  313. // 如果开启了异步变更值,则不修改内部的值,需要用户手动在外部通过v-model变更
  314. if (!this.asyncChange) {
  315. this.$nextTick(() => {
  316. console.log('emitChange', value)
  317. // #ifdef VUE2
  318. this.$emit('input', value)
  319. // #endif
  320. // #ifdef VUE3
  321. this.$emit('update:modelValue', value)
  322. // #endif
  323. this.currentValue = value
  324. this.$forceUpdate()
  325. })
  326. }
  327. this.$emit('change', {
  328. value,
  329. name: this.name,
  330. });
  331. },
  332. onChange() {
  333. const {
  334. type
  335. } = this
  336. if (this.isDisabled(type)) {
  337. return this.$emit('overlimit', type)
  338. }
  339. const diff = type === 'minus' ? -this.step : +this.step
  340. const value = this.format(this.add(+this.currentValue, diff))
  341. this.emitChange(value)
  342. this.$emit(type)
  343. },
  344. // 对值扩大后进行四舍五入,再除以扩大因子,避免出现浮点数操作的精度问题
  345. add(num1, num2) {
  346. const cardinal = Math.pow(10, 10);
  347. return Math.round((num1 + num2) * cardinal) / cardinal
  348. },
  349. // 点击加减按钮
  350. clickHandler(type) {
  351. this.type = type
  352. this.onChange()
  353. },
  354. longPressStep() {
  355. // 每隔一段时间,重新调用longPressStep方法,实现长按加减
  356. this.clearTimeout()
  357. this.longPressTimer = setTimeout(() => {
  358. this.onChange()
  359. this.longPressStep()
  360. }, 250);
  361. },
  362. onTouchStart(type) {
  363. if (!this.longPress) return
  364. this.clearTimeout()
  365. this.type = type
  366. // 一定时间后,默认达到长按状态
  367. this.longPressTimer = setTimeout(() => {
  368. this.onChange()
  369. this.longPressStep()
  370. }, 600)
  371. },
  372. // 触摸结束,清除定时器,停止长按加减
  373. onTouchEnd() {
  374. if (!this.longPress) return
  375. this.clearTimeout()
  376. },
  377. // 清除定时器
  378. clearTimeout() {
  379. clearTimeout(this.longPressTimer)
  380. this.longPressTimer = null
  381. }
  382. }
  383. }
  384. </script>
  385. <style lang="scss" scoped>
  386. @import '../../libs/css/components.scss';
  387. $u-numberBox-disabled-color: #c8c9cc !default;
  388. $u-numberBox-disabled-bgColor: #f7f8fa !default;
  389. $u-numberBox-plus-radius: 4px !default;
  390. $u-numberBox-minus-radius: 4px !default;
  391. $u-numberBox-input-text-align: center !default;
  392. $u-numberBox-input-font-size: 15px !default;
  393. $u-numberBox-input-padding: 0 !default;
  394. $u-numberBox-input-margin: 0 2px !default;
  395. $u-numberBox-input-disabled-color: #c8c9cc !default;
  396. $u-numberBox-input-disabled-bgColor: #f2f3f5 !default;
  397. .u-number-box {
  398. @include flex(row);
  399. align-items: center;
  400. &__slot {
  401. /* #ifndef APP-NVUE */
  402. touch-action: none;
  403. /* #endif */
  404. }
  405. &__plus,
  406. &__minus {
  407. width: 35px;
  408. @include flex;
  409. justify-content: center;
  410. align-items: center;
  411. /* #ifndef APP-NVUE */
  412. touch-action: none;
  413. /* #endif */
  414. &--disabled {
  415. color: $u-numberBox-disabled-color;
  416. background-color: $u-numberBox-disabled-bgColor;
  417. }
  418. }
  419. &__plus {
  420. border-top-right-radius: $u-numberBox-plus-radius;
  421. border-bottom-right-radius: $u-numberBox-plus-radius;
  422. }
  423. &__minus {
  424. border-top-left-radius: $u-numberBox-minus-radius;
  425. border-bottom-left-radius: $u-numberBox-minus-radius;
  426. }
  427. &__input {
  428. position: relative;
  429. text-align: $u-numberBox-input-text-align;
  430. font-size: $u-numberBox-input-font-size;
  431. padding: $u-numberBox-input-padding;
  432. margin: $u-numberBox-input-margin;
  433. @include flex;
  434. align-items: center;
  435. justify-content: center;
  436. border: 0;
  437. &--disabled {
  438. color: $u-numberBox-input-disabled-color;
  439. background-color: $u-numberBox-input-disabled-bgColor;
  440. }
  441. }
  442. }
  443. </style>