新建directive.js
import Vue from 'vue'
export default () => {
Vue.directive('Int', {
inserted: function (el) {
el.addEventListener("keypress",function(e){
e = e || window.event;
let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
let re = /\d/;
if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
});
}
});
}
全局注册
import Directive from '@/utils/directive.js'
Vue.use(Directive);
页面使用
<el-input placeholder="请输入" v-model.number="mobile" v-Int maxlength="11" ></el-input>
这篇博客介绍了如何在Vue.js中创建一个自定义指令`v-Int`,该指令用于限制用户在输入框中只能输入数字。通过监听`keypress`事件,阻止非数字字符的输入,确保输入值始终为整数。该指令可以全局注册并在页面上的`el-input`组件上使用,以实现手机号码等需要限制输入格式的情景。
4404

被折叠的 条评论
为什么被折叠?



