u-number-box.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. if(!this.canSmall) this.currentValue = this.format(this.value)
  191. else this.currentValue = 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. if(!this.canSmall){
  268. // 最大允许的小数长度
  269. if (this.decimalLength !== null && formatted.indexOf('.') !== -1) {
  270. const pair = formatted.split('.');
  271. formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`
  272. }
  273. formatted = this.format(formatted)
  274. }
  275. this.emitChange(formatted);
  276. },
  277. // 发出change事件
  278. emitChange(value) {
  279. // 如果开启了异步变更值,则不修改内部的值,需要用户手动在外部通过v-model变更
  280. if (!this.asyncChange) {
  281. this.$nextTick(() => {
  282. this.$emit('input', value)
  283. this.currentValue = value
  284. this.$forceUpdate()
  285. })
  286. }
  287. this.$emit('change', {
  288. value,
  289. name: this.name,
  290. });
  291. },
  292. onChange() {
  293. const {
  294. type
  295. } = this
  296. if (this.isDisabled(type)) {
  297. return this.$emit('overlimit', type)
  298. }
  299. const diff = type === 'minus' ? -this.step : +this.step
  300. const value = this.format(this.add(+this.currentValue, diff))
  301. this.emitChange(value)
  302. this.$emit(type)
  303. },
  304. // 对值扩大后进行四舍五入,再除以扩大因子,避免出现浮点数操作的精度问题
  305. add(num1, num2) {
  306. const cardinal = Math.pow(10, 10);
  307. return Math.round((num1 + num2) * cardinal) / cardinal
  308. },
  309. // 点击加减按钮
  310. clickHandler(type) {
  311. this.type = type
  312. this.onChange()
  313. },
  314. longPressStep() {
  315. // 每隔一段时间,重新调用longPressStep方法,实现长按加减
  316. this.clearTimeout()
  317. this.longPressTimer = setTimeout(() => {
  318. this.onChange()
  319. this.longPressStep()
  320. }, 250);
  321. },
  322. onTouchStart(type) {
  323. if (!this.longPress) return
  324. this.clearTimeout()
  325. this.type = type
  326. // 一定时间后,默认达到长按状态
  327. this.longPressTimer = setTimeout(() => {
  328. this.onChange()
  329. this.longPressStep()
  330. }, 600)
  331. },
  332. // 触摸结束,清除定时器,停止长按加减
  333. onTouchEnd() {
  334. if (!this.longPress) return
  335. this.clearTimeout()
  336. },
  337. // 清除定时器
  338. clearTimeout() {
  339. clearTimeout(this.longPressTimer)
  340. this.longPressTimer = null
  341. }
  342. }
  343. }
  344. </script>
  345. <style lang="scss" scoped>
  346. @import '../../libs/css/components.scss';
  347. $u-numberBox-hover-bgColor: #E6E6E6 !default;
  348. $u-numberBox-disabled-color: #c8c9cc !default;
  349. $u-numberBox-disabled-bgColor: #f7f8fa !default;
  350. $u-numberBox-plus-radius: 4px !default;
  351. $u-numberBox-minus-radius: 4px !default;
  352. $u-numberBox-input-text-align: center !default;
  353. $u-numberBox-input-font-size: 15px !default;
  354. $u-numberBox-input-padding: 0 !default;
  355. $u-numberBox-input-margin: 0 2px !default;
  356. $u-numberBox-input-disabled-color: #c8c9cc !default;
  357. $u-numberBox-input-disabled-bgColor: #f2f3f5 !default;
  358. .u-number-box {
  359. @include flex(row);
  360. align-items: center;
  361. &__slot {
  362. /* #ifndef APP-NVUE */
  363. touch-action: none;
  364. /* #endif */
  365. }
  366. &__plus,
  367. &__minus {
  368. width: 35px;
  369. @include flex;
  370. justify-content: center;
  371. align-items: center;
  372. /* #ifndef APP-NVUE */
  373. touch-action: none;
  374. /* #endif */
  375. &--hover {
  376. background-color: $u-numberBox-hover-bgColor !important;
  377. }
  378. &--disabled {
  379. color: $u-numberBox-disabled-color;
  380. background-color: $u-numberBox-disabled-bgColor;
  381. }
  382. }
  383. &__plus {
  384. border-top-right-radius: $u-numberBox-plus-radius;
  385. border-bottom-right-radius: $u-numberBox-plus-radius;
  386. }
  387. &__minus {
  388. border-top-left-radius: $u-numberBox-minus-radius;
  389. border-bottom-left-radius: $u-numberBox-minus-radius;
  390. }
  391. &__input {
  392. position: relative;
  393. text-align: $u-numberBox-input-text-align;
  394. font-size: $u-numberBox-input-font-size;
  395. padding: $u-numberBox-input-padding;
  396. margin: $u-numberBox-input-margin;
  397. @include flex;
  398. align-items: center;
  399. justify-content: center;
  400. &--disabled {
  401. color: $u-numberBox-input-disabled-color;
  402. background-color: $u-numberBox-input-disabled-bgColor;
  403. }
  404. }
  405. }
  406. </style>