赞
踩
实现只能输入数字,或输入2位或4位小数(通过传参控制)
toFixed.js
import Vue from "vue"; Vue.directive("toFixed", { componentUpdated(el, binding) { let toFixedLength = binding.value; if (!toFixedLength) { return false; } const ele: any = el.tagName === "INPUT" ? el : el.querySelector("input"); ele.addEventListener("input", () => { let val = ele.value; if (isNaN(val)) { ele.value = ""; return false; } if (typeof val === "number") { val = val.toString(); } if (typeof val === "string") { switch (toFixedLength) { case 2: val = val.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); break; case 4: val = val.replace(/^(-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3"); break; } ele.value = val; } }); }, });
// 正整数和浮点数输入自定义指令
import "@/directive/toFixed";
如果要保留4位小数
<el-input v-toFixed="4"></el-input>
如果要保留2位小数
<el-input v-toFixed="2"></el-input>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。