保留5位小数封装一个自定义指令
名为 decimalDirec 的 Vue 自定义指令,用于限制输入框中数字的小数位数
这个指令的主要功能是:
1.限制输入框中的数字最多只能有指定的小数位数(默认 5 位)
2.自动过滤非数字字符和非法的小数点
3.确保输入的数字格式正确(如自动补全前导零)
4.与 Vue 的数据绑定系统(v-model)正确集成
一、在utils文件夹下新建directives文件夹,新建decimalDirec.js
export const decimalDirec = {bind(el, binding) {// 指令第一次绑定到元素时调用,初始化设置const input = el.querySelector('input'); // 获取输入框元素const decimalPlaces = binding.value || 5; // 获取指令参数,默认5位小数input.addEventListener('input', function(e) {// 监听输入事件,每次输入变化时执行过滤逻辑let value = e.target.value;// 1. 过滤非数字和小数点字符value = value.replace(/[^\d.]/g, '');// 2. 处理小数点后的位数const dotIndex = value.indexOf('.');if (dotIndex !== -1) {// 保留第一个小数点之前的部分和之后的数字const integerPart = value.substring(0, dotIndex);const decimalPart = value.substring(dotIndex + 1).replace(/\./g, ''); // 移除所有后续小数点// 3. 限制小数位数为5位const truncatedDecimal = decimalPart.substring(0, 5);// 合并整数部分和小数部分value = `${integerPart}.${truncatedDecimal}`;}// 4. 处理前导小数点(如输入 .5 自动转换为 0.5)if (value.startsWith('.')) value = '0' + value;// 5. 更新输入框的值e.target.value = value;// 6. 手动触发 input 事件,通知 Vue 数据更新const event = new Event('input', { bubbles: true });e.target.dispatchEvent(event);});}
};
二、如何注册和使用自定义指令?
在main.js中引入import { decimalDirec } from '@/utils/directives/decimalDirec';// 注册全局保留小数点指令
Vue.directive('decimal', decimalDirec);<vxe-inputv-model="row.outOfMeters":disabled="showAble"placeholder="出库米数"type="number"v-decimal="5" />