u-number-box.vue 13 KB

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