You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

465 lines
14 KiB

2 months ago
  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. }
  261. },
  262. // 判断是否出于禁止操作状态
  263. // isDisabled(type) {
  264. // if (type === 'plus') {
  265. // // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  266. // return (
  267. // this.disabled ||
  268. // this.disablePlus ||
  269. // this.currentValue >= this.max
  270. // )
  271. // }
  272. // // 点击减少按钮同理
  273. // return (
  274. // this.disabled ||
  275. // this.disableMinus ||
  276. // this.currentValue <= this.min
  277. // )
  278. // },
  279. // 输入框活动焦点
  280. onFocus(event) {
  281. this.$emit('focus', {
  282. ...event.detail,
  283. name: this.name,
  284. })
  285. },
  286. // 输入框失去焦点
  287. onBlur(event) {
  288. // 对输入值进行格式化
  289. const value = this.format(event.detail.value)
  290. // 发出blur事件
  291. this.$emit(
  292. 'blur',{
  293. ...event.detail,
  294. name: this.name,
  295. }
  296. )
  297. },
  298. // 输入框值发生变化
  299. onInput(e) {
  300. const {
  301. value = ''
  302. } = e.detail || {}
  303. // 为空返回
  304. if (value === '') return
  305. let formatted = this.filter(value)
  306. // 最大允许的小数长度
  307. if (this.decimalLength !== null && formatted.indexOf('.') !== -1) {
  308. const pair = formatted.split('.');
  309. formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`
  310. }
  311. formatted = this.format(formatted)
  312. this.emitChange(formatted);
  313. // #ifdef MP-WEIXIN
  314. return formatted
  315. // #endif
  316. },
  317. // 发出change事件
  318. emitChange(value) {
  319. // 如果开启了异步变更值,则不修改内部的值,需要用户手动在外部通过v-model变更
  320. if (!this.asyncChange) {
  321. this.$nextTick(() => {
  322. // #ifdef VUE3
  323. this.$emit('update:modelValue', value)
  324. // #endif
  325. // #ifdef VUE2
  326. this.$emit('input', value)
  327. // #endif
  328. this.currentValue = value
  329. this.$forceUpdate()
  330. })
  331. }
  332. this.$emit('change', {
  333. value,
  334. name: this.name,
  335. });
  336. },
  337. onChange() {
  338. const {
  339. type
  340. } = this
  341. if (this.isDisabled(type)) {
  342. return this.$emit('overlimit', type)
  343. }
  344. const diff = type === 'minus' ? -this.step : +this.step
  345. const value = this.format(this.add(+this.currentValue, diff))
  346. this.emitChange(value)
  347. this.$emit(type)
  348. },
  349. // 对值扩大后进行四舍五入,再除以扩大因子,避免出现浮点数操作的精度问题
  350. add(num1, num2) {
  351. const cardinal = Math.pow(10, 10);
  352. return Math.round((num1 + num2) * cardinal) / cardinal
  353. },
  354. // 点击加减按钮
  355. clickHandler(type) {
  356. this.type = type
  357. this.onChange()
  358. },
  359. longPressStep() {
  360. // 每隔一段时间,重新调用longPressStep方法,实现长按加减
  361. this.clearTimeout()
  362. this.longPressTimer = setTimeout(() => {
  363. this.onChange()
  364. this.longPressStep()
  365. }, 250);
  366. },
  367. onTouchStart(type) {
  368. if (!this.longPress) return
  369. this.clearTimeout()
  370. this.type = type
  371. // 一定时间后,默认达到长按状态
  372. this.longPressTimer = setTimeout(() => {
  373. this.onChange()
  374. this.longPressStep()
  375. }, 600)
  376. },
  377. // 触摸结束,清除定时器,停止长按加减
  378. onTouchEnd() {
  379. if (!this.longPress) return
  380. this.clearTimeout()
  381. },
  382. // 清除定时器
  383. clearTimeout() {
  384. clearTimeout(this.longPressTimer)
  385. this.longPressTimer = null
  386. }
  387. }
  388. }
  389. </script>
  390. <style lang="scss" scoped>
  391. @import '../../libs/css/components.scss';
  392. $u-numberBox-hover-bgColor: #E6E6E6 !default;
  393. $u-numberBox-disabled-color: #c8c9cc !default;
  394. $u-numberBox-disabled-bgColor: #f7f8fa !default;
  395. $u-numberBox-plus-radius: 4px !default;
  396. $u-numberBox-minus-radius: 4px !default;
  397. $u-numberBox-input-text-align: center !default;
  398. $u-numberBox-input-font-size: 15px !default;
  399. $u-numberBox-input-padding: 0 !default;
  400. $u-numberBox-input-margin: 0 2px !default;
  401. $u-numberBox-input-disabled-color: #c8c9cc !default;
  402. $u-numberBox-input-disabled-bgColor: #f2f3f5 !default;
  403. .u-number-box {
  404. @include flex(row);
  405. align-items: center;
  406. &__slot {
  407. /* #ifndef APP-NVUE */
  408. touch-action: none;
  409. /* #endif */
  410. }
  411. &__plus,
  412. &__minus {
  413. width: 35px;
  414. @include flex;
  415. justify-content: center;
  416. align-items: center;
  417. /* #ifndef APP-NVUE */
  418. touch-action: none;
  419. /* #endif */
  420. &--hover {
  421. background-color: $u-numberBox-hover-bgColor !important;
  422. }
  423. &--disabled {
  424. color: $u-numberBox-disabled-color;
  425. background-color: $u-numberBox-disabled-bgColor;
  426. }
  427. }
  428. &__plus {
  429. border-top-right-radius: $u-numberBox-plus-radius;
  430. border-bottom-right-radius: $u-numberBox-plus-radius;
  431. }
  432. &__minus {
  433. border-top-left-radius: $u-numberBox-minus-radius;
  434. border-bottom-left-radius: $u-numberBox-minus-radius;
  435. }
  436. &__input {
  437. position: relative;
  438. text-align: $u-numberBox-input-text-align;
  439. font-size: $u-numberBox-input-font-size;
  440. padding: $u-numberBox-input-padding;
  441. margin: $u-numberBox-input-margin;
  442. @include flex;
  443. align-items: center;
  444. justify-content: center;
  445. &--disabled {
  446. color: $u-numberBox-input-disabled-color;
  447. background-color: $u-numberBox-input-disabled-bgColor;
  448. }
  449. }
  450. }
  451. </style>