vue 输入框数字增加千分位指令

609 阅读1分钟
// 数字加,号
function filterMoney(str) {
  // 将数字转换位字符串
  let num = ''
  // console.log(str,'STR==')
  if (str && str !== 0) {
    num = (str * 1).toFixed(2)
    if (isNaN(num)) {
      return ''
    }
  } else if(str === 0) {
    return 0
  }
  // 如果存在小数点,截取小数点及其后面的字符
  let after = num.indexOf('.') > 0 ? num.substr(num.indexOf('.')) : ''
  // 如果存在小数点,使用substring截取小数点前的字符,再通过split给字符串转换为数组
  let numArr = num.indexOf('.') > 0 ? num.substring(0, num.indexOf('.')) : num

  if (numArr && numArr !== null) {
    numArr = numArr.toString().replace(/\d+/, (n) => {
      return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
        return $1 + ','
      })
    })
  }
  // 再将数组转换为字符串,拼接上上面的小数点后面的字符
  return numArr + after

}
// 清除千分位
export function clearMoney(str) {
 // 将数字转换位字符串
 let num = ''
 if (str) {
   num = str + ''
 }
 return num.replace(/[^\d.]/g, "");
}
import { filterMoney,clearMoney } from "@/utils";
export default {
    bind(el, binding, vnode) {
        const { value } = binding
        const ele = el.children[0]
        el.custom = {
            value
        }
        const val = filterMoney(ele.value)
        ele.value = val
        ele.addEventListener('blur',(e) => {
            const val = filterMoney(ele.value)
            ele.value = val
        })
        ele.addEventListener('focus',(e) => {
            ele.value = clearMoney(ele.value) || ''
        })
        // throw new Error(`请设置操作权限标签值`)
    },
    update(el, binding, vnode) {
        const { value } = binding
        const ele = el.children[0]
        const val = filterMoney(ele.value)
        if(ele.target.value !== value) {
            return
        }

        ele.value = val
    }
}
import thousandth from './number/thousandth'
Vue.directive('thousandth',thousandth)
// html 使用
<el-input v-model.trim="value" v-thousandth></el-input>