创建 文件 global index.ts
main.ts文件引入
import global from "@/global"; app.use(global)
index.ts 内容
import { App } from "vue";
export default (app: App) => {
// 输入框限制几位正小数
app.directive("float", {
mounted(el, binding) {
let { value } = binding;
//digit:1=一位小数,2=两位小数,10=0位小数能输入o 正数,11=0位小数不能输入o 正数
let digit = value!=null||value!=undefined?value: 2;
let input = el.querySelector("input");
input.setAttribute("type", "text");
input.addEventListener("input", (val) => {
let { target: { value } } = val;
if (digit == 10){
val.target.value=value.replace(/^0+(\d)|[^\d]+/g,'');
}else if (digit == 11) {
val.target.value=value.replace(/^(0+)|[^\d]+/g,'');
} else if (digit == 1) {
val.target.value = value.replace(/^0[0-9]+/, val => val[1])
.replace(/^(\.)+/, "")
.replace(/[^\d.]/g, "")
.replace(/\.+/, ".")
.replace(/^(\-)*(\d+)\.(\d).*$/, "$1$2.$3");
} else {
val.target.value = value.replace(/^0[0-9]+/, val => val[1])
.replace(/^(\.)+/, "")
.replace(/[^\d.]/g, "")
.replace(/\.+/, ".")
.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
}
});
},
unmounted(el) {
let input = el.querySelector("input");
input.addEventListener("input", () => {
});
}
});
}
使用方式
<el-input v-float="10" :maxlength="3" type="number" v-model.number="value" ></el-input>
<el-input v-float="11" :maxlength="3" type="number" v-model.number="value" ></el-input>
<el-input v-float="2" type="number" v-model.trim="value"></el-input>
标签:digit,val,自定义,vue3,value,replace,let,input,小数位 From: https://www.cnblogs.com/FACESCORE/p/16955721.html