input数字输入框,自定义保留小数位数,禁止输入多个小数点,以及对非数字字符的处理
作者:互联网
input数字输入框,自定义保留小数位数,禁止输入多个小数点,以及对非数字字符的处理
<template>
<input class="numberInput" type="number" :placeholder="placeholder" v-model="inputData" @keydown="keydownFn" />
</template>
<script>
export default {
props: {
point: {
default: 0
},
max: Number,
placeholder: String,
value: {
default: null
},
},
computed: {
inputData: {
get:function() {
return this.value;
},
set:function (value) {
let val = this.$el.value;
let len = val.length;
// 若输入08,变为8
if(len==2 && val.charAt(0)==0 && val.charAt(1)!='.'){
this.$el.value = val.charAt(1);
this.setParentModeVal(this.$el.value);
return;
}
// 禁止输入多个小数点
if(Math.abs(this.value) > 0 && val==='' && value ===''){
if(this.keyDownDel){
this.$el.value = '';
}else {
this.$el.value = this.value;
}
this.setParentModeVal(this.$el.value);
return ;
}
// 处理输入“点、e、+、-等被识别为数字字符
if(this.value === '' && val === '' && value === ''){ //字母类非数字输入都为'';
this.$el.value = '';
this.setParentModeVal('');
return ;
}
// 保留小数
if(val){
let pointIndex = val.indexOf('.');
if(this.point==0 && pointIndex!== -1){
this.$el.value = val.substr(0, pointIndex);
this.setParentModeVal(this.$el.value);
return ;
}
if(pointIndex>0 && (len - pointIndex)>(this.point+1)){
this.$el.value = val.substr(0,pointIndex + this.point +1);
this.setParentModeVal(this.$el.value);
return ;
}
}
// 最大值
if(this.max>0 && val>this.max){
this.$el.value = val.substr(0,len-1);
this.setParentModeVal(this.$el.value);
return;
}
this.setParentModeVal(val);
return;
}
}
},
data() {
return {
keyDownDel: false,// 判断键盘输入值
}
},
methods: {
setParentModeVal(value){
this.$emit('input', value);
},
keydownFn(event){
let e = event || window.event;
if(e.keyCode==8||e.keyCode==46){ //Backspace || Delete
this.keyDownDel = true;
}else {
this.keyDownDel = false;
}
}
},
}
</script>
<style lang="less" scoped>
.numberInput {
width: 100%;
vertical-align: middle;
border-radius: 4px;
border: 1px solid #dcdee2; //变换边框样式
padding: 4px 7px;
height: 32px;
color: #515a6e;
outline:medium; //去除默认鼠标点击边框样式
}
.numberInput:hover {
border-color: #f75b46;
}
.numberInput:focus {
border-color: #f75b46;
outline: 0;
box-shadow: 0 0 0 2px rgba(245, 50, 24, .2);
}
input::-webkit-input-placeholder {
color: #c5c8ce;
}
// input::-webkit-inner-spin-button, //去掉右侧加减的小箭头
// input::-webkit-outer-spin-button {
// -webkit-appearance: none;
// margin: 0;
// }
</style>
引入代码:
import numberInput from '~/components/common/numberInput';
<numberInput :point="2" :min="0" placeholder="请输入金额" v-model="formData.amount"></numberInput>
标签:el,return,数字,val,value,setParentModeVal,&&,对非,自定义 来源: https://blog.csdn.net/wang_xiao_ye/article/details/96136454