<el-input>只能输入数字,保留两位小数
实现思路
单独做一个组件来实现额外的功能
只能输入数字: 监听input事件,在监听函数中通过正则处理掉非字符
保留两位小数: 监听blur事件,在失去焦点时格式化为2位小数,对于从prop中进来的value属性每次都进行格式化
完整代码
<template>
<el-input
v-model="inputValue"
@blur="onBlur"
@input="onInput"/>
</template>
<script>
const debounce=(func,awit,immediately)=>{//防抖函数
var timer;
return function(){
var self=this;
if(immediately && !timer){
func.call(self)
}
if(timer)
clearTimeout(timer);
timer=setTimeout(function(){
func.call(self)
},awit)
}
}
const toDecimal2=(x)=>{//格式化函数
if(x.split('.').length>2){
x=x.split('.').slice(0,2).join('.');
}
var f = parseFloat(x);
if (isNaN(f)) {
return '0.00';
}
f = Math.round(x*100)/100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
export default {
props:{
value:{
}
},
data(){
return {
inputValue:this.value,
emitEvent:debounce(()=>{
this.$emit('input',this.inputValue)
},1000)
}
},
watch:{
value(){
this.inputValue=toDecimal2(this.value)
}
},
methods:{
onBlur(){
this.inputValue=toDecimal2(this.inputValue);
},
onInput(value){
this.inputValue = value.replace(/[^\d.]/g,'');
this.emitEvent()
}
}
}
</script>
浙公网安备 33010602011771号