当前位置: 首页 > Web前端 > HTML

使用vue自定义指令实现输入框的输入限制

时间:2023-03-28 18:18:15 HTML

一直想做一个可以统一处理输入框限制的小工具。最近需要新项目,所以借用了大佬们的文档博客,自己记录下来。废话不多说,直接上代码://index.vue//directive.jsimportVuefrom'vue'//只能输入带小数点的数字的限制由修饰符constonlyNum=控制(el,bindings,vnode)=>{letregExp=/[^\d]/gif(bindings.modifiers['point']){//修饰符'point'regExp=/[^\d\.]/g}fnSaveCursorPos(el,bindings,vnode,regExp)}//只限制字母(包括大小写字母)constonlyLetter=(el,bindings,vnode)=>{letregExp=/[^a-z|A-Z]/gif(bindings.modifiers['point']){//Modifier'point'regExp=/[^a-z|A-Z|.]/g}fnSaveCursorPos(el,bindings,vnode,regExp)}//限制只让字母和数字(包括大小写字母)constonlyLetterNum=(el,bindings,vnode)=>{letregExp=/[^a-z|A-Z\d]/gfnSaveCursorPos(el,bindings,vnode,regExp)}Vue.directive('input-filter',{update(el,bindings,vnode){switch(bindings.arg){case'num':onlyNum(el,bindings,vnode)breakcase'letter':onlyLetter(el,bindings,vnode)breakcase'num-letter':onlyLetterNum(el,bindings,vnode)breakdefault:console.log('Thismethodhasnoadditions')break}}})//处理光标位置避免restarting赋值后光标出现在末尾el.querySelector('input')}if(!inputEl){console.log('noinput')return}constinputElCursorPos=inputEl.selectionStart//输入框输入后的光标位置constregExpStringLength=(bindings.value.match(regExp)||[]).length//清除的字符长度fnSetVal(vnode.context,bindings.expression,bindings.value.replace(regExp,''))inputEl.setSelectionRange(inputElCursorPos-regExpStringLength,输入ElCursorPos-regExpStringLength)consttimer=setTimeout(()=>{//console.log('inputEl',inputElCursorPos-regExpStringLength)clearTimeout(timer)inputEl.setSelectionRange(inputElCursorPos-regExpStringLength,inputElCursorPos-regExpStringLength)})}//赋值处理,例如:obj.key.keyfunctionfnSetVal(data,fields,setVal){if(Object.prototype.toString.call(data)==='[objectObject]'&&Object.prototype.toString.call(fields)==='[objectString]'){constkeys=fields.split('.')letvalue=datawhile(keys.length&&value!==undefined){if(keys.length===1){值[keys[0]]=setValreturn}value=value[keys[0]]keys.shift()}}}在自定义指令中使用'update'的生命周期来处理绑定值,但是这样会有是两个更新过程,第一个是原始值触发的更新,第二个是处理限制后触发的更新;我觉得这并不完美。文中如有问题请指出~~~谢谢!!!