index.vue 1.42 KB
<template>
    <el-input :value="value" v-bind="$attrs" v-on="{...$listeners}"  @blur="blurFn"></el-input>
</template>
  
<script>
export default {
    name: 'FormatInput',
    props: ['value','precise','intDigit','maxVal','minVal'],
    data() {
      return {
        
      }
    },
    watch:{
      value:{
        handler(nVal, oVal){
          this.inputFn(nVal)
        },
        deep: true
      }
    },
    mounted(){
    },
    methods:{
      inputFn(e){
        e = e ? String(e) : ''
        this.intDigit = this.intDigit || 6
        this.precise =  this.precise || 2
        let value = e
        if(this.maxVal){
          if(+this.maxVal<= +e) value =  this.maxVal  //加等号是因为 '500' == '500.' 导致多了点
        }else{
          const intDigitReg = this.intDigit == -1 ? `(^\\d+)(\\.\\d+)?` :  `(^\\d{${this.intDigit}})\\d+(\\.\\d+)?`
          value = e.replace(/^0\d/g, '0').replace(/[^\d.]/g, '').replace(/^\./g, '').replace(new RegExp(intDigitReg,'g'), '$1').replace('.', '$#$')
                .replace(/\./g, '').replace('$#$', '.').replace(new RegExp(`^(-)*(\\d+)\\.(\\d{${this.precise}}).*$`),  this.intDigit == -1 ? '$1$2' :  '$1$2.$3')
        }
        this.$emit('input', value)
      },
      blurFn(e){
        let value = e.target.value
        if(this.minVal && +this.minVal>=value) value = this.minVal
        this.$emit('input', value)
      }
    }
  }
</script>
<style lang="scss" scoped>
</style>