u-number-box.vue 14 KB

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