需求:“只允許輸入金額保留兩位小數”,有2種實現方法
方法一(通過正則控制):
html:
<el-inputv-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;
},
方法二(使用組件):
這個是我最近才發現的,方便多了TT
設置精度precision,即可四舍五入;
再改改樣式,隱藏按鈕,靠左對齊,最后效果和普通的input無異
<el-input-number v-model="num" :precision="2"></el-input-number>