最近写了个发单页面,输入框要求限制最多两位小数,如果不填默认值为0,个别需要为整数。 刚开始想法是使用一个公共方法处理传入的值,然后把处理后的返回回来。这样写发现特别麻烦,每个输入框都要在change事件中调用这个方法重新赋值,后面想到了能否用自定义指令来实现。
使用方法(三种)
<input v-formartIput />输入框为两位小数
<input v-formartIput.integer />输入框为整数
<input v-formartIput='{def: 0}' />设置输入框默认填充值
设置自定义指令(单页面)
directives: {
formatInput: function(el, binding){
//不可以直接用el,刚开始直接用el时用antdv输入框时候获取不到this.value值
const inputDom = el.querySelector('input')?el.querySelector('input'):el
const handleFun = function(){
//转为字符串类型
inputDom.value = inputDom.value.toString()
// 保留数字和.
inputDom.value = inputDom.value.replace(/[^\d.]/g, '')
//----如果是integer只保留数字
if(binding.modifiers.integer) {
inputDom.value = inputDom.value.replace(/[^\d]/g, "")
}
// 去除输入框中开头多余的0
inputDom.value = (/^0\d/.test(inputDom.value))? inputDom.value.replace(/^0/,'') : inputDom.value
// inputDom.value = inputDom.value.replace(/^0{2,}/,'0')
// 输入 . 自动填充为 0.
inputDom.value = inputDom.value.replace(/^\./,'0.')
// 只保留一个 .
inputDom.value = inputDom.value.replace(/\./,'%$%$%').replace(/\./g, '').replace('%$%$%', '.');
// 限制小数位数
let tm = inputDom.value.split('.')
if(tm[1]) {
tm[1] = tm[1].substring(0,2)
}
inputDom.value = tm.join('.')
}
// !!!使用addEventListen 监听input和blur有点问题,改为这种
inputDom.oninput = function(e){
handleFun()
}
inputDom.onblur = function(){
// 在失去焦点之后再进行设置默认值
if(!this.value&&binding.value&&(binding.value.def||binding.value.def===0)) {
this.value = binding.value.def
}
handleFun()
//如果有默认值就失去焦点时候填充默认值
// 不加下面这个输入框没变化不是事实更新
const event = document.createEvent('Event')
event.initEvent('input', true, true)
this.dispatchEvent(event)
}
}
},
目前这三种格式化满足自己的需求