金额输入千分位组件及其他各种限制

115 阅读1分钟
<template>
  <el-input
    v-model="input"
    :maxlength="maxlength"
    :placeholder="placeholder"
    @blur="moneyRender()"
    @focus="moneyInput"
  ></el-input>
</template>

<script>
export default {
  props: {
    value: String | Number,
    maxlength: { type: String, default: '10' },
    placeholder: { type: Number, default: 0 },
  },
  data() {
    return {
      input: '',
    };
  },
  mounted() {
    this.moneyRender(this.value);
  },
  methods: {
    moneyRender(val) {
      const value = val || this.input;//可能会有传入的数据
      const reg1 = /0*([1-9]\d*|0.\d+)/;//去掉小数点前首位的0
      const reg2 = /(?:.0*|(.\d+?)0+)$/;//去掉小数点后末尾的0
      let result = String(value).replace(reg1, '$1').replace(reg2, '$1'); // 如果输入的是正确的金额,则去掉头尾无用的0
      this.input = this.trimNumber(result).replace(reg2, '$1');//添加千分位&处理非数字无效字符并去掉小数点后可能多出来的0
      this.$emit('input', this.input.replaceAll(',', ''));//抛出的数据不带千分位
    },
    trimNumber(val) {
      const value = val || this.input;
      let pre = String(value);
      let after = '';
      if (pre.indexOf('.') > -1) {
        after = `.${pre.split('.')[1].replaceAll(/\D/g, '')}`;//小数点后不加千分位
        pre = pre.split('.')[0];//只有一位小数点且不在首位或末尾
      }
      pre = pre.replaceAll(/\D/g, '');
     
      if (/^0+$/.test(pre)) {  // 判断是否全部都是0
        return '0';
      }
      const reg = /(\d)(?=(?:\d{3})+$)/g;//处理无效字符
      pre = pre.replace(reg, '$1,');//每三位加千分位
      if (after !== '') {
        after = Number(`0${after}`).toFixed(2).slice(1);//小数点后最多保留两位小数
      }
      return pre + after;
    },
    moneyInput() {
      this.input = String(this.input).replaceAll(',', ''); //聚焦时去掉小数点(防止输入位数出现问题)
    },
  },
};
</script>
```
```