因为公司业务涉及到很多的金额输入框,在网上找了很久也没找到符合我预期的完美输入框
,今天特地写了一个,基本满足日常的金额输入。
实现效果:
- 只能输入数字0-9和小数点
- 支持将中文输入法句号转变成小数点
- 将小数点开头的数字转变成0.开头
- 将第一位是0且第二位不是小数点的数前面的0省略
- 限制小数位数及金额字符串的总位数
- input聚焦和失焦自动切换标准金额显示
效果图:
不多废话,上代码!
Template
// Template
<template>
<div>
<el-form inline>
<el-form-item label="完美的金额输入框">
<el-input v-model="a" @blur="amountBlur" @focus="amountFocus"></el-input>
</el-form-item>
</el-form>
</div>
</template>
script setup
// script setup
<script setup lang="ts">
import {ref, watch} from 'vue'
import common from "../../utils/common";
let a = ref('');
let temp = 'temp'
const amountFocus = function () {
a.value = temp
temp = 'temp'
}
const amountBlur = function () {
temp = a.value;
a.value = common.amountFormat(a.value,2,true);
}
amountBlur()
watch(a,(newVal, oldValue) => {
// 临时变量不为'temp'时不启动监听
if(temp !== 'temp') return
// pc端中文输入法'。' ==> '.'
let newStr = (newVal+'').replace('。','.').replace(/[^0-9.]/g,'')
let oldStr = oldValue+''
// .xxx ==> 0.xxx
if(newStr.startsWith('.')) {
newStr = '0.' + newStr.slice(1)
}
// 0xxx ==> xxx
if(newStr.startsWith('0') && newStr.length>1 && !newStr.slice(1).startsWith('.')) {
newStr = newStr.slice(1)
}
// 限制小数点数量、小数点后两位小数、金额字符串总长度
if(newStr.split('.').length>2 || (newStr.split('.').length==2 && newStr.split('.')[1].length>2) || newStr.length>10){
newStr = oldStr;
}
a.value = newStr
})
</script>
下面是common.amountFormat方法的实现:
// common
/**
* 金额格式化
* @param amount 金额String||Number
* @param precision 小数位数Number(0-20)
* @param unit 是否带单位Boolean
* @returns {string}
*/
amountFormat: function(amount, precision, unit) {
if(amount == '') amount = '0'
precision = precision > 0 && precision <= 20 ? precision : 2;
amount = parseFloat((amount + "").replace(/[^\d\.-]/g, "")).toFixed(precision) + "";
let l = amount.split(".")[0].split("").reverse();
let r = amount.split(".")[1];
let t = "";
for (let i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
if(unit) {
return t.split("").reverse().join("") + "." + r + '元';
} else {
return t.split("").reverse().join("") + "." + r;
}
}