u-number-box.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. /**
  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. *
  103. * @event {Function} onFocus 输入框活动焦点
  104. * @event {Function} onBlur 输入框失去焦点
  105. * @event {Function} onInput 输入框值发生变化
  106. * @event {Function} onChange
  107. * @example <u-number-box v-model="value" @change="valChange"></u-number-box>
  108. */
  109. export default {
  110. name: 'u-number-box',
  111. mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
  112. data() {
  113. return {
  114. // 输入框实际操作的值
  115. currentValue: '',
  116. // 定时器
  117. longPressTimer: null
  118. }
  119. },
  120. watch: {
  121. // 多个值之间,只要一个值发生变化,都要重新检查check()函数
  122. watchChange(n) {
  123. this.check()
  124. },
  125. // 监听v-mode的变化,重新初始化内部的值
  126. value(n) {
  127. if (n !== this.currentValue) {
  128. this.currentValue = this.format(this.value)
  129. }
  130. }
  131. },
  132. computed: {
  133. getCursorSpacing() {
  134. // 判断传入的单位,如果为px单位,需要转成px
  135. return uni.$u.getPx(this.cursorSpacing)
  136. },
  137. // 按钮的样式
  138. buttonStyle() {
  139. return (type) => {
  140. const style = {
  141. backgroundColor: this.bgColor,
  142. height: uni.$u.addUnit(this.buttonSize),
  143. color: this.color
  144. }
  145. if (this.isDisabled(type)) {
  146. style.backgroundColor = '#f7f8fa'
  147. }
  148. return style
  149. }
  150. },
  151. // 输入框的样式
  152. inputStyle() {
  153. const disabled = this.disabled || this.disabledInput
  154. const style = {
  155. color: this.color,
  156. backgroundColor: this.bgColor,
  157. height: uni.$u.addUnit(this.buttonSize),
  158. width: uni.$u.addUnit(this.inputWidth)
  159. }
  160. return style
  161. },
  162. // 用于监听多个值发生变化
  163. watchChange() {
  164. return [this.integer, this.decimalLength, this.min, this.max]
  165. },
  166. isDisabled() {
  167. return (type) => {
  168. if (type === 'plus') {
  169. // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  170. return (
  171. this.disabled ||
  172. this.disablePlus ||
  173. this.currentValue >= this.max
  174. )
  175. }
  176. // 点击减少按钮同理
  177. return (
  178. this.disabled ||
  179. this.disableMinus ||
  180. this.currentValue <= this.min
  181. )
  182. }
  183. },
  184. },
  185. mounted() {
  186. this.init()
  187. },
  188. methods: {
  189. init() {
  190. this.currentValue = this.format(this.value)
  191. },
  192. // 格式化整理数据,限制范围
  193. format(value) {
  194. value = this.filter(value)
  195. // 如果为空字符串,那么设置为0,同时将值转为Number类型
  196. value = value === '' ? 0 : +value
  197. // 对比最大最小值,取在min和max之间的值
  198. value = Math.max(Math.min(this.max, value), this.min)
  199. // 如果设定了最大的小数位数,使用toFixed去进行格式化
  200. if (this.decimalLength !== null) {
  201. value = value.toFixed(this.decimalLength)
  202. }
  203. return value
  204. },
  205. // 过滤非法的字符
  206. filter(value) {
  207. // 只允许0-9之间的数字,"."为小数点,"-"为负数时候使用
  208. value = String(value).replace(/[^0-9.-]/g, '')
  209. // 如果只允许输入整数,则过滤掉小数点后的部分
  210. if (this.integer && value.indexOf('.') !== -1) {
  211. value = value.split('.')[0]
  212. }
  213. return value;
  214. },
  215. check() {
  216. // 格式化了之后,如果前后的值不相等,那么设置为格式化后的值
  217. const val = this.format(this.currentValue);
  218. if (val !== this.currentValue) {
  219. this.currentValue = val
  220. }
  221. },
  222. // 判断是否出于禁止操作状态
  223. // isDisabled(type) {
  224. // if (type === 'plus') {
  225. // // 在点击增加按钮情况下,判断整体的disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
  226. // return (
  227. // this.disabled ||
  228. // this.disablePlus ||
  229. // this.currentValue >= this.max
  230. // )
  231. // }
  232. // // 点击减少按钮同理
  233. // return (
  234. // this.disabled ||
  235. // this.disableMinus ||
  236. // this.currentValue <= this.min
  237. // )
  238. // },
  239. // 输入框活动焦点
  240. onFocus(event) {
  241. this.$emit('focus', {
  242. ...event.detail,
  243. name: this.name,
  244. })
  245. },
  246. // 输入框失去焦点
  247. onBlur(event) {
  248. // 对输入值进行格式化
  249. const value = this.format(event.detail.value)
  250. // 发出blur事件
  251. this.$emit(
  252. 'blur',{
  253. ...event.detail,
  254. name: this.name,
  255. }
  256. )
  257. },
  258. // 输入框值发生变化
  259. onInput(e) {
  260. const {
  261. value = ''
  262. } = e.detail || {}
  263. // 为空返回
  264. if (value === '') return
  265. let formatted = this.filter(value)
  266. // 最大允许的小数长度
  267. if (this.decimalLength !== null && formatted.indexOf('.') !== -1) {
  268. const pair = formatted.split('.');
  269. formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`
  270. }
  271. formatted = this.format(formatted)
  272. this.emitChange(formatted);
  273. },
  274. // 发出change事件
  275. emitChange(value) {
  276. // 如果开启了异步变更值,则不修改内部的值,需要用户手动在外部通过v-model变更
  277. if (!this.asyncChange) {
  278. this.$nextTick(() => {
  279. this.$emit('input', value)
  280. this.currentValue = value
  281. this.$forceUpdate()
  282. })
  283. }
  284. this.$emit('change', {
  285. value,
  286. name: this.name,
  287. });
  288. },
  289. onChange() {
  290. const {
  291. type
  292. } = this
  293. if (this.isDisabled(type)) {
  294. return this.$emit('overlimit', type)
  295. }
  296. const diff = type === 'minus' ? -this.step : +this.step
  297. const value = this.format(this.add(+this.currentValue, diff))
  298. this.emitChange(value)
  299. this.$emit(type)
  300. },
  301. // 对值扩大后进行四舍五入,再除以扩大因子,避免出现浮点数操作的精度问题
  302. add(num1, num2) {
  303. const cardinal = Math.pow(10, 10);
  304. return Math.round((num1 + num2) * cardinal) / cardinal
  305. },
  306. // 点击加减按钮
  307. clickHandler(type) {
  308. this.type = type
  309. this.onChange()
  310. },
  311. longPressStep() {
  312. // 每隔一段时间,重新调用longPressStep方法,实现长按加减
  313. this.clearTimeout()
  314. this.longPressTimer = setTimeout(() => {
  315. this.onChange()
  316. this.longPressStep()
  317. }, 250);
  318. },
  319. onTouchStart(type) {
  320. if (!this.longPress) return
  321. this.clearTimeout()
  322. this.type = type
  323. // 一定时间后,默认达到长按状态
  324. this.longPressTimer = setTimeout(() => {
  325. this.onChange()
  326. this.longPressStep()
  327. }, 600)
  328. },
  329. // 触摸结束,清除定时器,停止长按加减
  330. onTouchEnd() {
  331. if (!this.longPress) return
  332. this.clearTimeout()
  333. },
  334. // 清除定时器
  335. clearTimeout() {
  336. clearTimeout(this.longPressTimer)
  337. this.longPressTimer = null
  338. }
  339. }
  340. }
  341. </script>
  342. <style lang="scss" scoped>
  343. @import '../../libs/css/components.scss';
  344. $u-numberBox-hover-bgColor: #E6E6E6 !default;
  345. $u-numberBox-disabled-color: #c8c9cc !default;
  346. $u-numberBox-disabled-bgColor: #f7f8fa !default;
  347. $u-numberBox-plus-radius: 4px !default;
  348. $u-numberBox-minus-radius: 4px !default;
  349. $u-numberBox-input-text-align: center !default;
  350. $u-numberBox-input-font-size: 15px !default;
  351. $u-numberBox-input-padding: 0 !default;
  352. $u-numberBox-input-margin: 0 2px !default;
  353. $u-numberBox-input-disabled-color: #c8c9cc !default;
  354. $u-numberBox-input-disabled-bgColor: #f2f3f5 !default;
  355. .u-number-box {
  356. @include flex(row);
  357. align-items: center;
  358. &__slot {
  359. /* #ifndef APP-NVUE */
  360. touch-action: none;
  361. /* #endif */
  362. }
  363. &__plus,
  364. &__minus {
  365. width: 35px;
  366. @include flex;
  367. justify-content: center;
  368. align-items: center;
  369. /* #ifndef APP-NVUE */
  370. touch-action: none;
  371. /* #endif */
  372. &--hover {
  373. background-color: $u-numberBox-hover-bgColor !important;
  374. }
  375. &--disabled {
  376. color: $u-numberBox-disabled-color;
  377. background-color: $u-numberBox-disabled-bgColor;
  378. }
  379. }
  380. &__plus {
  381. border-top-right-radius: $u-numberBox-plus-radius;
  382. border-bottom-right-radius: $u-numberBox-plus-radius;
  383. }
  384. &__minus {
  385. border-top-left-radius: $u-numberBox-minus-radius;
  386. border-bottom-left-radius: $u-numberBox-minus-radius;
  387. }
  388. &__input {
  389. position: relative;
  390. text-align: $u-numberBox-input-text-align;
  391. font-size: $u-numberBox-input-font-size;
  392. padding: $u-numberBox-input-padding;
  393. margin: $u-numberBox-input-margin;
  394. @include flex;
  395. align-items: center;
  396. justify-content: center;
  397. &--disabled {
  398. color: $u-numberBox-input-disabled-color;
  399. background-color: $u-numberBox-input-disabled-bgColor;
  400. }
  401. }
  402. }
  403. </style>