1、在test.js中创建amountInput方法
// 金额输入框 限制输入方法
export function amountInput(val) {
if (!val) val = '';
if (typeof val !== 'string') val += '';
if (val.substr(0, 1) === '.') val = '';
val = val.replace(/^0*(0\.|[1-9])/, '$1'); //解决 粘贴不生效
val = val.replace(/[^\d.]/g, ''); //清除“数字”和“.”以外的字符
val = val.replace(/^00/, '0'); //小数前只能输入一个0
val = val.replace(/^\./g, ''); //清除. 字符开头
val = val.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
if (val.indexOf('.') < 0 && val !== '') {
if (val.substr(0, 1) === '0' && val.length === 2) {
val = val.substr(1, val.length);
}
}
return val;
}
2、在main.js中引用
自定义指令函数传参
import { amountInput } from '@/utils/test';
Vue.prototype.amountInput = amountInput;
Vue.directive('amountInput', {
bind(el,binding, vnode) {
// input输入框 限制输入方法
const inputDom = el.querySelector('input');
inputDom.oninput = () => {
//将input框值替换为修改过的值
inputDom.value = amountInput(inputDom.value);
//binding.value传入的参(浅说一下,页面input框触发的input事件获取的值并不是修改后的值,这里可通过binding传入的方法和参数,处理数据)
};
},
});
3、
3.1页面input框没有用到input方法的可以不传参
//使用自定义指令
v-amountInput
<el-form-item
:prop="'list.' + scope.$index + '.dose'"
:rules="[{ required: 'true', trigger: 'change' }]"
>
<el-input
v-model="scope.row.dose"
placeholder="请输入"
:ref="'tabFocusDose' + scope.$index"
@keydown.native.enter="doseEnter"
v-amountInput
></el-input>
{{ scope.row.dunitStr }}
</el-form-item>
3.2在页面中调用,input框触发input事件调用方法changeQuantity,scope.row(table行数据)
//将需要调用的方法传入
v-amountInput="{ fun: changeQuantity, data: scope.row }"
<el-form-item
:prop="'list.' + scope.$index + '.dose'"
:rules="[{ required: 'true', trigger: 'change' }]"
>
<el-input
v-model="scope.row.dose"
placeholder="请输入"
:ref="'tabFocusDose' + scope.$index"
@keydown.native.enter="doseEnter"
v-amountInput="{ fun: changeQuantity, data: scope.row }"
></el-input>
{{ scope.row.dunitStr }}
</el-form-item>