1.在utils文件夹下新建一个directives.js文件(命名自己随意)
2.directives.js文件内容如下
const enterNumber = (el, binding) => {
const wins0 = /[^\d]/g; // 整数判断
const wins1 = /[^\d^\.]/g; // 小数判断
let flag = true;
let points = 0;
let lengths = 0;
let remainder = 0;
let noint = 0;
const target = el instanceof HTMLInputElement ? el : el.querySelector('input');
target.addEventListener('compositionstart', e => {
flag = false;
});
target.addEventListener('compositionend', e => {
flag = true;
});
target.addEventListener('input', e => {
setTimeout(() => {
if (flag) {
if (binding.value === 0) {
if (wins0.test(e.target.value)) {
e.target.value = e.target.value.replace(/^(\-)*(\d{1})*$/, '$1$2');
e.target.dispatchEvent(new Event('input')); // 手动更新v-model值
}
}
if (binding.value === 1) {
e.target.value = e.target.value.replace(/^(\-)*(\d{1})*$/, '$1$2');
if (wins0.test(e.target.value)) {
remainder = true;
}
if ((e.target.value.split('.')).length - 1 > 1) {
points = true;
}
if (e.target.value.toString().split('.')[1] !== undefined) {
if (e.target.value.toString().split('.')[1].length > 1) {
lengths = true;
}
}
if (e.target.value.toString().indexOf('.') !== -1) {
noint = false;
} else {
noint = true;
}
if (wins1.test(e.target.value) || lengths || points || remainder) {
if (!noint) {
e.target.value = e.target.value.indexOf('.') > 0 ? e.target.value.replace(wins1, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3').substring(0, e.target.value.indexOf('.') + 2) : e.target.value.replace(wins0, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').substring(0, 1);
} else {
e.target.value = e.target.value.replace(/^(\-)*(\d{1})*$/, '$1$2');
}
e.target.dispatchEvent(new Event('input'));
}
}
if (binding.value === 2) {
if (wins0.test(e.target.value.toString().replace(/^(\-)*(\d{1})*$/, '$1$2'))) {
remainder = true;
}
if ((e.target.value.split('.')).length - 1 > 1) {
points = true;
}
if (e.target.value.toString().split('.')[1] !== undefined) {
if (e.target.value.toString().split('.')[1].length > 2) {
lengths = true;
}
}
if (e.target.value.toString().indexOf('.') !== -1) {
noint = false;
} else {
noint = true;
}
if (wins1.test(e.target.value) || lengths || points || remainder) {
if (!noint) {
e.target.value = e.target.value.replace(wins1, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').substring(0, e.target.value.indexOf('.') + 3);
} else {
e.target.value = e.target.value.replace(/^(\-)*(\d{1})*$/, '$1$2');
}
e.target.dispatchEvent(new Event('input'));
}
}
}
}, 0);
});
};
export default enterNumber;
3.在main.js中注册全局指令
import enterNumber from '@/utils/directives.js'; // 引入鼠标拖拽滚动图片指令文件
// 注册输入框限制图片指令
Vue.directive('enterNumber', enterNumber);
4.最后在组件中使用
<input v-model="num" type="number" v-enterNumber="1">