封装el-input组件,限制输入为数值类型(vue)
<template>
<el-input
v-bind="$attrs"
v-on="$listeners"
v-model="inputVal"
@input.native="inputHandle($event, isInteger, isZero, decimalCount)"
></el-input>
</template>
<script>
export default {
name: "InputNumber",
inheritAttrs: false,
props: {
fieldValue: {
default: "",
},
isInteger: {
type: Boolean,
default: true,
},
isZero: {
type: Boolean,
default: true,
},
decimalCount: {
type: Number,
default: 2,
},
callback: {
type: Function,
default: null,
},
},
data() {
return {
inputVal: "",
originVal: "",
};
},
watch: {
fieldValue: {
handler(val) {
this.originVal = this.inputVal = val;
},
immediate: true,
},
},
methods: {
inputHandle(e, isInteger, isZero, decimalCount) {
if (e.target.value === "") {
this.originVal = "";
this.$emit("update:fieldValue", "");
if (this.callback) this.callback("");
return;
}
let rule = /.*/;
if (isInteger) {
if (isZero) {
rule = /^\d*$/;
} else {
rule = /^[1-9]\d*$/;
}
} else {
rule = new RegExp(`^\\d+\\.?\\d{0,${decimalCount}}$`);
}
if (rule.test(e.target.value)) {
if (isInteger || /^0+[^.]/.test(e.target.value)) {
this.inputVal = e.target.value = Number(e.target.value)
}
this.originVal = this.inputVal;
this.$emit("update:fieldValue", this.inputVal);
if (this.callback) this.callback(this.inputVal);
} else {
this.inputVal = e.target.value = this.originVal;
}
},
},
};
</script>
<template>
<div class="home">
<h1>This is an home page</h1>
<hr />
<InputNumber :fieldValue.sync="iptVal" />
<p>-----{{ iptVal }}-----</p>
</div>
</template>
<script>
import InputNumber from "@/components/mycompo/InputNumber.vue";
export default {
name: "HomeView",
components: {
InputNumber,
},
data() {
return {
iptVal: "",
};
},
};
</script>
|