bug
jiangping
2023-11-07 64b432916af9c9218ab3f3eca614e26c542142ae
minipro_standard/uni_modules/uview-ui/components/u-number-box/u-number-box.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,416 @@
<template>
   <view class="u-number-box">
      <view
          class="u-number-box__slot"
          @tap.stop="clickHandler('minus')"
          @touchstart="onTouchStart('minus')"
          @touchend.stop="clearTimeout"
          v-if="showMinus && $slots.minus"
      >
         <slot name="minus" />
      </view>
      <view
          v-else-if="showMinus"
          class="u-number-box__minus"
          @tap.stop="clickHandler('minus')"
          @touchstart="onTouchStart('minus')"
          @touchend.stop="clearTimeout"
          hover-class="u-number-box__minus--hover"
          hover-stay-time="150"
          :class="{ 'u-number-box__minus--disabled': isDisabled('minus') }"
          :style="[buttonStyle('minus')]"
      >
         <u-icon
             name="minus"
             :color="isDisabled('minus') ? '#c8c9cc' : '#323233'"
             size="15"
             bold
            :customStyle="iconStyle"
         ></u-icon>
      </view>
      <slot name="input">
         <input
             :disabled="disabledInput || disabled"
             :cursor-spacing="getCursorSpacing"
             :class="{ 'u-number-box__input--disabled': disabled || disabledInput }"
             v-model="currentValue"
             class="u-number-box__input"
             @blur="onBlur"
             @focus="onFocus"
             @input="onInput"
             type="number"
             :style="[inputStyle]"
         />
      </slot>
      <view
          class="u-number-box__slot"
          @tap.stop="clickHandler('plus')"
          @touchstart="onTouchStart('plus')"
          @touchend.stop="clearTimeout"
          v-if="showPlus && $slots.plus"
      >
         <slot name="plus" />
      </view>
      <view
          v-else-if="showPlus"
          class="u-number-box__plus"
          @tap.stop="clickHandler('plus')"
          @touchstart="onTouchStart('plus')"
          @touchend.stop="clearTimeout"
          hover-class="u-number-box__plus--hover"
          hover-stay-time="150"
          :class="{ 'u-number-box__minus--disabled': isDisabled('plus') }"
          :style="[buttonStyle('plus')]"
      >
         <u-icon
             name="plus"
             :color="isDisabled('plus') ? '#c8c9cc' : '#323233'"
             size="15"
             bold
            :customStyle="iconStyle"
         ></u-icon>
      </view>
   </view>
</template>
<script>
   import props from './props.js';
   /**
    * numberBox æ­¥è¿›å™¨
    * @description è¯¥ç»„件一般用于商城购物选择物品数量的场景。
    * @tutorial https://uviewui.com/components/numberBox.html
    * @property {String | Number}   name         æ­¥è¿›å™¨æ ‡è¯†ç¬¦ï¼Œåœ¨change回调返回
    * @property {String | Number}   value         ç”¨äºŽåŒå‘绑定的值,初始化时设置设为默认min值(最小值)  ï¼ˆé»˜è®¤ 0 ï¼‰
    * @property {String | Number}   min            æœ€å°å€¼ ï¼ˆé»˜è®¤ 1 ï¼‰
    * @property {String | Number}   max            æœ€å¤§å€¼ ï¼ˆé»˜è®¤ Number.MAX_SAFE_INTEGER ï¼‰
    * @property {String | Number}   step         åŠ å‡çš„æ­¥é•¿ï¼Œå¯ä¸ºå°æ•° ï¼ˆé»˜è®¤ 1 ï¼‰
    * @property {Boolean}         integer         æ˜¯å¦åªå…è®¸è¾“入整数 ï¼ˆé»˜è®¤ false ï¼‰
    * @property {Boolean}         disabled      æ˜¯å¦ç¦ç”¨ï¼ŒåŒ…括输入框,加减按钮 ï¼ˆé»˜è®¤ false ï¼‰
    * @property {Boolean}         disabledInput   æ˜¯å¦ç¦ç”¨è¾“入框 ï¼ˆé»˜è®¤ false ï¼‰
    * @property {Boolean}         asyncChange      æ˜¯å¦å¼€å¯å¼‚步变更,开启后需要手动控制输入值 ï¼ˆé»˜è®¤ false ï¼‰
    * @property {String | Number}   inputWidth      è¾“入框宽度,单位为px ï¼ˆé»˜è®¤ 35 ï¼‰
    * @property {Boolean}         showMinus      æ˜¯å¦æ˜¾ç¤ºå‡å°‘按钮 ï¼ˆé»˜è®¤ true ï¼‰
    * @property {Boolean}         showPlus      æ˜¯å¦æ˜¾ç¤ºå¢žåŠ æŒ‰é’® ï¼ˆé»˜è®¤ true ï¼‰
    * @property {String | Number}   decimalLength   æ˜¾ç¤ºçš„小数位数
    * @property {Boolean}         longPress      æ˜¯å¦å¼€å¯é•¿æŒ‰åŠ å‡æ‰‹åŠ¿ ï¼ˆé»˜è®¤ true ï¼‰
    * @property {String}         color         è¾“入框文字和加减按钮图标的颜色 ï¼ˆé»˜è®¤ '#323233' ï¼‰
    * @property {String | Number}   buttonSize      æŒ‰é’®å¤§å°ï¼Œå®½é«˜ç­‰äºŽæ­¤å€¼ï¼Œå•位px,输入框高度和此值保持一致 ï¼ˆé»˜è®¤ 30 ï¼‰
    * @property {String}         bgColor         è¾“入框和按钮的背景颜色 ï¼ˆé»˜è®¤ '#EBECEE' ï¼‰
    * @property {String | Number}   cursorSpacing   æŒ‡å®šå…‰æ ‡äºŽé”®ç›˜çš„距离,避免键盘遮挡输入框,单位px ï¼ˆé»˜è®¤ 100 ï¼‰
    * @property {Boolean}         disablePlus      æ˜¯å¦ç¦ç”¨å¢žåŠ æŒ‰é’® ï¼ˆé»˜è®¤ false ï¼‰
    * @property {Boolean}         disableMinus   æ˜¯å¦ç¦ç”¨å‡å°‘按钮 ï¼ˆé»˜è®¤ false ï¼‰
    * @property {Object ï½œ String}   iconStyle      åŠ å‡æŒ‰é’®å›¾æ ‡çš„æ ·å¼
    *
    * @event {Function}   onFocus   è¾“入框活动焦点
    * @event {Function}   onBlur   è¾“入框失去焦点
    * @event {Function}   onInput   è¾“入框值发生变化
    * @event {Function}   onChange
    * @example <u-number-box v-model="value" @change="valChange"></u-number-box>
    */
   export default {
      name: 'u-number-box',
      mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
      data() {
         return {
            // è¾“入框实际操作的值
            currentValue: '',
            // å®šæ—¶å™¨
            longPressTimer: null
         }
      },
      watch: {
         // å¤šä¸ªå€¼ä¹‹é—´ï¼Œåªè¦ä¸€ä¸ªå€¼å‘生变化,都要重新检查check()函数
         watchChange(n) {
            this.check()
         },
         // ç›‘听v-mode的变化,重新初始化内部的值
         value(n) {
            if (n !== this.currentValue) {
               this.currentValue = this.format(this.value)
            }
         }
      },
      computed: {
         getCursorSpacing() {
            // åˆ¤æ–­ä¼ å…¥çš„单位,如果为px单位,需要转成px
            return uni.$u.getPx(this.cursorSpacing)
         },
         // æŒ‰é’®çš„æ ·å¼
         buttonStyle() {
            return (type) => {
               const style = {
                  backgroundColor: this.bgColor,
                  height: uni.$u.addUnit(this.buttonSize),
                  color: this.color
               }
               if (this.isDisabled(type)) {
                  style.backgroundColor = '#f7f8fa'
               }
               return style
            }
         },
         // è¾“入框的样式
         inputStyle() {
            const disabled = this.disabled || this.disabledInput
            const style = {
               color: this.color,
               backgroundColor: this.bgColor,
               height: uni.$u.addUnit(this.buttonSize),
               width: uni.$u.addUnit(this.inputWidth)
            }
            return style
         },
         // ç”¨äºŽç›‘听多个值发生变化
         watchChange() {
            return [this.integer, this.decimalLength, this.min, this.max]
         },
         isDisabled() {
            return (type) => {
               if (type === 'plus') {
                  // åœ¨ç‚¹å‡»å¢žåŠ æŒ‰é’®æƒ…å†µä¸‹ï¼Œåˆ¤æ–­æ•´ä½“çš„disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
                  return (
                     this.disabled ||
                     this.disablePlus ||
                     this.currentValue >= this.max
                  )
               }
               // ç‚¹å‡»å‡å°‘按钮同理
               return (
                  this.disabled ||
                  this.disableMinus ||
                  this.currentValue <= this.min
               )
            }
         },
      },
      mounted() {
         this.init()
      },
      methods: {
         init() {
            this.currentValue = this.format(this.value)
         },
         // æ ¼å¼åŒ–整理数据,限制范围
         format(value) {
            value = this.filter(value)
            // å¦‚果为空字符串,那么设置为0,同时将值转为Number类型
            value = value === '' ? 0 : +value
            // å¯¹æ¯”最大最小值,取在min和max之间的值
            value = Math.max(Math.min(this.max, value), this.min)
            // å¦‚果设定了最大的小数位数,使用toFixed去进行格式化
            if (this.decimalLength !== null) {
               value = value.toFixed(this.decimalLength)
            }
            return value
         },
         // è¿‡æ»¤éžæ³•的字符
         filter(value) {
            // åªå…è®¸0-9之间的数字,"."为小数点,"-"为负数时候使用
            value = String(value).replace(/[^0-9.-]/g, '')
            // å¦‚果只允许输入整数,则过滤掉小数点后的部分
            if (this.integer && value.indexOf('.') !== -1) {
               value = value.split('.')[0]
            }
            return value;
         },
         check() {
            // æ ¼å¼åŒ–了之后,如果前后的值不相等,那么设置为格式化后的值
            const val = this.format(this.currentValue);
            if (val !== this.currentValue) {
               this.currentValue = val
            }
         },
         // åˆ¤æ–­æ˜¯å¦å‡ºäºŽç¦æ­¢æ“ä½œçŠ¶æ€
         // isDisabled(type) {
         //    if (type === 'plus') {
         //       // åœ¨ç‚¹å‡»å¢žåŠ æŒ‰é’®æƒ…å†µä¸‹ï¼Œåˆ¤æ–­æ•´ä½“çš„disabled,是否单独禁用增加按钮,以及当前值是否大于最大的允许值
         //       return (
         //          this.disabled ||
         //          this.disablePlus ||
         //          this.currentValue >= this.max
         //       )
         //    }
         //    // ç‚¹å‡»å‡å°‘按钮同理
         //    return (
         //       this.disabled ||
         //       this.disableMinus ||
         //       this.currentValue <= this.min
         //    )
         // },
         // è¾“入框活动焦点
         onFocus(event) {
            this.$emit('focus', {
               ...event.detail,
               name: this.name,
            })
         },
         // è¾“入框失去焦点
         onBlur(event) {
            // å¯¹è¾“入值进行格式化
            const value = this.format(event.detail.value)
            // å‘出blur事件
            this.$emit(
               'blur',{
                  ...event.detail,
                  name: this.name,
               }
            )
         },
         // è¾“入框值发生变化
         onInput(e) {
            const {
               value = ''
            } = e.detail || {}
            // ä¸ºç©ºè¿”回
            if (value === '') return
            let formatted = this.filter(value)
            // æœ€å¤§å…è®¸çš„小数长度
            if (this.decimalLength !== null && formatted.indexOf('.') !== -1) {
               const pair = formatted.split('.');
               formatted = `${pair[0]}.${pair[1].slice(0, this.decimalLength)}`
            }
            formatted = this.format(formatted)
            this.emitChange(formatted);
         },
         // å‘出change事件
         emitChange(value) {
            // å¦‚果开启了异步变更值,则不修改内部的值,需要用户手动在外部通过v-model变更
            if (!this.asyncChange) {
               this.$nextTick(() => {
                  this.$emit('input', value)
                  this.currentValue = value
                  this.$forceUpdate()
               })
            }
            this.$emit('change', {
               value,
               name: this.name,
            });
         },
         onChange() {
            const {
               type
            } = this
            if (this.isDisabled(type)) {
               return this.$emit('overlimit', type)
            }
            const diff = type === 'minus' ? -this.step : +this.step
            const value = this.format(this.add(+this.currentValue, diff))
            this.emitChange(value)
            this.$emit(type)
         },
         // å¯¹å€¼æ‰©å¤§åŽè¿›è¡Œå››èˆäº”入,再除以扩大因子,避免出现浮点数操作的精度问题
         add(num1, num2) {
            const cardinal = Math.pow(10, 10);
            return Math.round((num1 + num2) * cardinal) / cardinal
         },
         // ç‚¹å‡»åŠ å‡æŒ‰é’®
         clickHandler(type) {
            this.type = type
            this.onChange()
         },
         longPressStep() {
            // æ¯éš”一段时间,重新调用longPressStep方法,实现长按加减
            this.clearTimeout()
            this.longPressTimer = setTimeout(() => {
               this.onChange()
               this.longPressStep()
            }, 250);
         },
         onTouchStart(type) {
            if (!this.longPress) return
            this.clearTimeout()
            this.type = type
            // ä¸€å®šæ—¶é—´åŽï¼Œé»˜è®¤è¾¾åˆ°é•¿æŒ‰çŠ¶æ€
            this.longPressTimer = setTimeout(() => {
               this.onChange()
               this.longPressStep()
            }, 600)
         },
         // è§¦æ‘¸ç»“束,清除定时器,停止长按加减
         onTouchEnd() {
            if (!this.longPress) return
            this.clearTimeout()
         },
         // æ¸…除定时器
         clearTimeout() {
            clearTimeout(this.longPressTimer)
            this.longPressTimer = null
         }
      }
   }
</script>
<style lang="scss" scoped>
   @import '../../libs/css/components.scss';
   $u-numberBox-hover-bgColor: #E6E6E6 !default;
   $u-numberBox-disabled-color: #c8c9cc !default;
   $u-numberBox-disabled-bgColor: #f7f8fa !default;
   $u-numberBox-plus-radius: 4px !default;
   $u-numberBox-minus-radius: 4px !default;
   $u-numberBox-input-text-align: center !default;
   $u-numberBox-input-font-size: 15px !default;
   $u-numberBox-input-padding: 0 !default;
   $u-numberBox-input-margin: 0 2px !default;
   $u-numberBox-input-disabled-color: #c8c9cc !default;
   $u-numberBox-input-disabled-bgColor: #f2f3f5 !default;
   .u-number-box {
      @include flex(row);
      align-items: center;
      &__slot {
         /* #ifndef APP-NVUE */
         touch-action: none;
         /* #endif */
      }
      &__plus,
      &__minus {
         width: 35px;
         @include flex;
         justify-content: center;
         align-items: center;
         /* #ifndef APP-NVUE */
         touch-action: none;
         /* #endif */
         &--hover {
            background-color: $u-numberBox-hover-bgColor !important;
         }
         &--disabled {
            color: $u-numberBox-disabled-color;
            background-color: $u-numberBox-disabled-bgColor;
         }
      }
      &__plus {
         border-top-right-radius: $u-numberBox-plus-radius;
         border-bottom-right-radius: $u-numberBox-plus-radius;
      }
      &__minus {
         border-top-left-radius: $u-numberBox-minus-radius;
         border-bottom-left-radius: $u-numberBox-minus-radius;
      }
      &__input {
         position: relative;
         text-align: $u-numberBox-input-text-align;
         font-size: $u-numberBox-input-font-size;
         padding: $u-numberBox-input-padding;
         margin: $u-numberBox-input-margin;
         @include flex;
         align-items: center;
         justify-content: center;
         &--disabled {
            color: $u-numberBox-input-disabled-color;
            background-color: $u-numberBox-input-disabled-bgColor;
         }
      }
   }
</style>