欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue2.x directive - 限制input只能输入正整数

程序员文章站 2022-03-13 18:14:18
onlyNum.js main.js 在component中只需要在input上加上v-limitNum就能生效。 ......

onlyNum.js

import Vue from 'vue'
//只对input生效
export default function (el) {
    var input = el;
    input.onkeyup = function (e) {
        if(input.value.length==1){
            input.value = input.value.replace(/[^1-9]/g,'');
        }else{
            input.value = input.value.replace(/[^\d]/g, "");
        }
    };
}

main.js

import limitNum from './directive/onlyNum'

Vue.directive('limitNum', limitNum);

在component中只需要在input上加上v-limitNum就能生效。