日常开发记录-el-input限制只能输入数字,千分位格式展示并且只保留两位小数

组件代码:

<template>
  <el-input
    v-bind="{
        clearable: true,
    }"
    v-model="input"
    @blur="blur"
    @focus="focus"
    placeholder="请输入内容">
    <template slot="append" v-if="suffix!==''" >{{ suffix }}</template>
  </el-input>
</template>

<script>
export default {
  props: {
    suffix: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      input: ''
    }
  },
  methods: {
    blur () {
      if (this.input === '') {
        this.input = ''
      } else {
        this.input = Math.round(this.input * Math.pow(10, 2)) / Math.pow(10, 2) // 四舍五入
        this.input = Number(this.input).toFixed(2) // 不足补位
        //   金额千分位转换1000 --> 1,000
        this.input = isNaN(Number(this.input)) ? '' : Number(this.input).toLocaleString()
      }
    },
    focus () {
      if ((this.input + '').trim() === '') {
        return ''
      }
      //    金额千分位格式逆转换1,000 --> 1000
      this.input = this.input.replace(/,/gi, '')
      this.input = Math.round(this.input * Math.pow(10, 2)) / Math.pow(10, 2) // 四舍五入
      this.input = Number(this.input).toFixed(2) // 不足补位
      return this.input
    }
  }
}
</script>
<style scoped lang='scss'>

</style>

效果展示:

 

posted on 2022-08-02 15:58  法老的微笑  阅读(1725)  评论(0)    收藏  举报