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