element input 输入数字转换成千分位

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>千分位</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/theme-chalk/index.min.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.1/index.min.js"></script>
  </head>
  <body>
    <div id="app">
      <el-input v-model.trim="form.pastAdjustFee" @focus="focus($event,'pastAdjustFee')" @blur="inputMoney($event,'pastAdjustFee')"></el-input>
    </div>
    <script>
      const MoneyTest = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
 
      // 金额添加千分位
      const comdify = function (n) {
        if (!n) return n
        let str = n.split('.')
        let re = /\d{1,3}(?=(\d{3})+$)/g
        let n1 = str[0].replace(re, '$&,')
        return str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`
      }
      //去除千分位中的‘,’
      const delcommafy = function (num) {
        if (!num) return num
        num = num.toString()
        num = num.replace(/,/gi, '')
        return num
      }
      const valdateFn = function (rule, val, cb) {
        setTimeout(() => {
          if (val) {
            let inputVal = delcommafy(val)
            if (rule.test(inputVal)) {
              cb()
            } else {
              cb('只能是数字金额,最多两位小数')
            }
          }
          cb()
        })
      }
      // 验证金额数字可以为负数
      const moneyValid = function (rule, val, cb) {
        valdateFn(/((^-?[1-9]\d*)|^-?0)(\.\d{0,2}){0,1}$/, val, cb)
      }
      // 验证金额数字不可以为负数
      const moneyNValid = function (rule, val, cb) {
        valdateFn(MoneyTest, val, cb)
      }
 
      // 获取输入框的值
      const getInputValue = function (el) {
        let inputVal = el.target.value || ''
        return comdify(delcommafy(inputVal))
      }
 
      const lx = new Vue({
        el: '#app',
        data() {
          return {
            form: {
              pastAdjustFee: '',
            },
          }
        },
        watch: {},
        computed: {},
        methods: {
          focus(el, name) {
            this.form[name] = ''
          },
          inputMoney(el, name) {
            this.form[name] = getInputValue(el)
          },
        },
        created() {},
      })
    </script>
 
    <style>
      .inline {
        display: flex;
      }
    </style>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值