u-number-box.vue 14 KB

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