描述
描述 项目中经常碰到一些要在文本输入框中只能输入数字或指定位数的小数的要求,如果可以做一个统一的指令,将这部分需求封装复用,使用起来会方便很多。
以下是对小数输入限制封装的指令 float.js:
//输入框限制小数的输入规则,可限制指定小数点前的输入长度、指定小数点后的位数
const specialInputFloatContext = '@@specialInputFloatContext';
export default {
bind: function (el,binding,vNode) {
let {totalDigit=1,pointAfterDigit=1}=binding.value;
let dealInputVal=(value,pointAfterDigit=0)=> {
value = value.replace(/^0*(0\.|[1-9])/, "$1");
value = value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
value = value.replace(/^\./g, ""); //验证第一个字符是数字而不是字符
value = value.replace(/\.{1,}/g, "."); //只保留第一个.清除多余的
value = value
.replace(".", "$#$")
.replace(/\./g, "")
.replace("$#$", ".");
let str='';
for(let i=0;i<pointAfterDigit;i++){
str+='\\d';
}
let reg=new RegExp('^(-)*(\\d*)\\.('+str+').*$');
value = value.replace(reg, "$1$2.$3"); //// value = value.replace(/^(-)*(\d*)\.(\d\d\d).*$/, "$1$2.$3");
value =
value.indexOf(".") > 0 ? value.split(".")[0].substring(0, totalDigit) + "." + value.split(".")[1] : value.substring(0, totalDigit);
return value;
}
const documentHandler = function(e) {
// const input = el.getElementsByTagName('input')[0] //element-ui el-input组件
const input = el;//input标签
let value=dealInputVal(input.value,pointAfterDigit);
input.value=value
vNode.data.model.callback(value)
};
el[specialInputFloatContext] = {
documentHandler,
arg: 'keyup',
};
document.addEventListener(el[specialInputFloatContext].arg, documentHandler);
},
unbind(el) {
document.removeEventListener(
el[specialInputFloatContext].arg,
el[specialInputFloatContext].documentHandler);
},
install(Vue) {
Vue.directive('float', {
bind: this.bind,
unbind: this.unbind
});
}
}
使用:限制小数点前5位,小数点后2位:
<input type="text" v-model.number.trim="float" v-float='{totalDigit:5,pointAfterDigit:2}' autoComplete="off" />