项目开发中需要用到一个数字输入框,只能输入4位整数和1位小数,用饿了么的input框将其type设置为"number"的话右边会有很丑的上下箭头。决定自己用input事件和blur事件实现同样的功能。自定义组件代码直接放下面,防止以后要用到:
源代码:
<template>
<el-input
:style="styleProp"
v-bind:value="value"
@input="change"
@blur="blur"
:placeholder="placeholder"
:disabled="!!disabled"
></el-input>
</template>
<script>
export default {
name: "NumberInput",
props: {
value: {
default: "",
},
// 小数位数
decimalCount: {
default: 1,
required: false,
},
// 整数位数
integer: {
default: 4,
required: false,
},
placeholder: {
default: "请输入",
},
// 样式
styleProp: {
default: "",
},
disabled: {
required: false,
},
},
data() {
return {
latestValue: "",
};
},
methods: {
updateValue(newVal) {
this.$emit("input", newVal);
this.latestValue = newVal;
},
change(v) {
let realValue = "";
const reg = new RegExp(
`^(\\d{0,${this.integer}})((\\.)(\\d{0,${this.decimalCount}})?)?$`
);
if (reg.test(v)) {
this.latestValue = v;
realValue = v;
} else {
realValue = this.latestValue;
}
this.updateValue(realValue);
},
blur() {
let realValue = "" + this.value;
if (!realValue) return;
if (realValue === ".") realValue = "0";
this.updateValue(parseFloat(realValue));
},
},
};
</script>
<style></style>
由于input事件和blur事件是input通用的,因此如果要用到其他框架或原生组件上也是可以的。