当前位置: 首页 > Web前端 > vue.js

vue2elementuiinput输入格式限制

时间:2023-03-31 17:33:39 vue.js

importVuefrom"vue";/***element-input输入限制**///v-positiveInteger正整数//v-positiveInteger.2保留两位小数//v-positiveInteger.4保留四位小数Vue.指令("positiveInteger",{bind(el,binding,vnode){letdom=findDom(el,"el-input__inner");letmodifiers=binding.modifiersletmantissa=0for(letxinmodifiers){mantissa=x}el.handler=function(){if(vnode.inputLocking){return;}if(mantissa){letreg=newRegExp(`^\\D*(\\d*(?:\.\\d{0,${尾数}})?).*$`,'gmi')el.childNodes[1].value=el.childNodes[1].value.replace(reg,"$1");}else{el.childNodes[1].value=el.childNodes[1].value.replace(/\D+/g,"");}dom.dispatchEvent(newEvent("input"));};dom.addEventListener("compositionstart",()=>{vnode.inputLocking=true;});dom.addEventListener("compositionend",()=>{vnode.inputLocking=false;dom.dispatchEvent(newEvent("input"));});dom.onfocus=function(){if(dom.value==0){dom.value="";}};el.addEventListener("keyup",el.handler);el.handler1=function(){el.childNodes[1].value=el.childNodes[1].value;dom.dispatchEvent(newEvent("input"));};el.childNodes[1].addEventListener("blur",el.handler1);},unbind(el){el.removeEventListener("keyup",el.handler);el.childNodes[1].removeEventListener("blur",el.handler);},});//递归查找某个元素节点functionfindDom(el,className){letdom;for(leti=0;i-1){dom=el.childNodes[i];休息;}else{dom=findDom(el.childNodes[i],className);}}}returndom;}参考文章