bash
<!-- 封装的价格表单组件 -->
<template>
<el-input :value="value" :placeholder="placeholder" @input="handleInput" />
</template>
<script>
export default {
name: "PriceInput",
props: {
value: {
type: [String, Number],
default: "",
},
placeholder: {
type: String,
default: "请输入",
},
},
methods: {
handleInput(value) {
// 如果完全删除输入,直接传递空值
if (value === "") {
this.$emit("input", "");
return;
}
// 仅允许数字和小数点
let newValue = value.replace(/[^\d.]/g, "");
// 限制只能有一个小数点
const parts = newValue.split(".");
if (parts.length > 2) {
newValue = parts[0] + "." + parts.slice(1).join("");
}
// 再次拆分整数和小数部分
const finalParts = newValue.split(".");
let integerPart = finalParts[0];
let decimalPart = finalParts.length > 1 ? finalParts[1] : undefined;
// 处理整数部分:去除前导零,但保留至少一个零
if (integerPart !== undefined && integerPart !== "") {
integerPart = integerPart.replace(/^0+/, "");
if (integerPart === "") integerPart = "0";
} else {
integerPart = "0";
}
// 限制小数部分最多两位
if (decimalPart !== undefined && decimalPart.length > 2) {
decimalPart = decimalPart.substring(0, 2);
}
// 重组最终字符串
let result = integerPart;
if (decimalPart !== undefined) {
result += "." + decimalPart;
}
this.$emit("input", result);
},
},
};
</script>
也可以使用组件el-input-number,可参考链接,但注意处理后格式为String了。