限制 el-input 输入格式(保留小数)vue3+ts
1.utils 创建文件 InputFloat.js
import { DirectiveBinding } from 'vue';
interface InputFloatOptions {
limit: number;
min?: number;
max?: number;
}
const vInputFloat = {
mounted(el: HTMLElement, binding: DirectiveBinding<InputFloatOptions>) {
const input = el instanceof HTMLInputElement ? el : el.querySelector('input');
if (!input) return;
const handleInput = () => {
let value = input.value.replace(/,/g, '').replace(/[^0-9.]/g, '');
if (value === '') {
input.value = '';
return;
}
const { limit, min, max } = binding.value;
const parts = value.split('.');
if (parts.length > 1 && parts[1].length > limit) {
parts[1] = parts[1].substring(0, limit);
}
let newValue = parts.join('.');
if (min !== undefined && parseFloat(newValue) < min) {
newValue = min.toString();
}
if (max !== undefined && parseFloat(newValue) > max) {
newValue = max.toString();
}
if (input.value !== newValue) {
input.value = newValue;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
};
input.addEventListener('input', handleInput);
}
};
export default vInputFloat;
2.main.js 引入自定义指令
import InputFloat from '@/utils/InputFloat' // elinput 限制小数点
app.directive('input-float', InputFloat);
3.使用
<el-input
v-model="form.price"
placeholder="请输入"
v-input-float="{ limit: 1, min: 0, max: 999999 }"
></el-input>