好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

vue实现input文本框只能输入0-99的正整数问题

vue input文本框只能输入0-99的正整数

利用vue里面自带的watch监听器就可以了。话不多说,直接贴代码。

? ? ? ? ? ? <div class="age-select">
? ? ? ? ? ? <input type="text" class="fromAge-input" v-model="fromAge" />至
? ? ? ? ? ? <input type="text" class="toAge-input" v-model="toAge" />
? ? ? ? ? ? </div>

data里面

? ? ?data () { return{?
? ? ? fromAge: '0',?
? ? ? ?toAge: '99'
? ? ? ?}?
? ? ? ?}

在watch里面:

? ? watch: {
? ? ? ? fromAge (newName, oldName) {
? ? ? ? ? var reg = /^([1-9]\d|\d)$/
? ? ? ? ? if (!reg.test(newName)) {
? ? ? ? ? ? this.fromAge = ''
? ? ? ? ? } else {
? ? ? ? ? ? this.fromAge = newName
? ? ? ? ? }
? ? ? ? },
? ? ? ? toAge (newName, oldName) {
? ? ? ? ? var reg = /^([1-9]\d|\d)$/
? ? ? ? ? if (!reg.test(newName)) {
? ? ? ? ? ? this.toAge = ''
? ? ? ? ? } else {
? ? ? ? ? ? this.toAge = newName
? ? ? ? ? }
? ? ? ? }
? ? ? },

效果如下:

这里输入框只能输入0-99的正整数,如果不是的话就会清空掉数字。如果我们还想加入前面的数字不能大于后面的数字的话,我们只需要在需要的方法里面加一个判定条件就可以了。代码如下:

     if (this.fromAge > this.toAge) {                    /* 如果起始年龄大于结束年龄的话,显示提示框 */
            return this.$message.error('起始年龄不能大于结束年龄')
          }

效果如下:

通过自定义指令实现文本框只能输入正整数

directives: {
    numInput(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;
          }
        }
      });
    },
  },

使用

?<input type="text" v-numInput ?/>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

查看更多关于vue实现input文本框只能输入0-99的正整数问题的详细内容...

  阅读:43次