需求:“只允許輸入金額保留兩位小數”,有2種實現方法
方法一(通過正則控制):
html:
<el-input
v-model="inputTable.amount"
@input="formatNum(form.amount, 'amount')"
></el-input>
js:
formatNum(val, key) {
let temp = val.toString();
temp = temp.replace(/。/g, ".");
temp = temp.replace(/[^\d.]/g, ""); //清除"數字"和"."以外的字符
temp = temp.replace(/^\./g, ""); //驗證第一個字符是數字
temp = temp.replace(/\.{2,}/g, ""); //只保留第一個, 清除多余的
temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能輸入兩個小數
this.form[key] = temp;
},
方法二(使用組件):
InputNumber 計數器
組件 | Element
precision配精度為兩位小數
<el-input-number v-model="num" :precision="2"></el-input-number>