当前位置 博文首页 > vue 限制input只能输入正数的操作

    vue 限制input只能输入正数的操作

    作者:你眼中的柔情 时间:2021-08-22 17:45

    在某些项目中 input 框只能输入数字,可以用以下办法:

    先在标签上绑定上 @input 事件来监听标签的值变化,通过正则来改变输入的值。

     <input
      class="keep_input"
      v-number-only
      style="width:35px"
      v-model="scope.row.fileOrder"
      @input="scope.row.fileOrder = Number($event.target.value.replace(/\D+/, ''))"
     />

    第二部封装个自定义指令放在标签上!

     directives: {
      numberOnly: {
       bind: function(el) {
        el.handler = function() {
         el.value = Number(el.value.replace(/\D+/, ''))
        }
        el.addEventListener('input', el.handler)
       },
       unbind: function(el) {
        el.removeEventListener('input', el.handler)
       }
      }
     },

    接下来就可以去页面看效果了,只能输入数字且只是正数!

    附上 element 的 input 样式代码

     .keep_input {
      -webkit-appearance: none;
      background-color: #fff;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #606266;
      display: inline-block;
      font-size: inherit;
      outline: 0;
      padding: 0 15px;
      -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      height: 30px;
      line-height: 30px;
      text-align: left;
     }
     .keep_input:focus {
      border-color: #54a6de;
      outline: 0;
     }

    补充知识:记录el-input type=number限制长度el-input使用

    如下所示:

    <el-input type="number"
     oninput="if(value.length>10)value=value.slice(0,10)"
     @keyup.enter.native="query()"
     onKeypress="return(/[\d\.]/.test(String.fromCharCode(event.keyCode)))"
     :max="99999999">
     </el-input>

    oninput 是个自定义事件 在事件里面获取输入的数字长度,来进行判断如果大于规定长度就进行剪切。

    keyup.enter.native 是个键盘回车事件,当按下Enter键时触发query()事件。

    max为输入框的最大值,如果input的type=number那么输入框内是输入不了字符的。

    number框 解决输入e的问题

    主要原因是:e在数学上代表的是无理数,是一个无限不循环的小数,其值约为2.7182818284,所以在输入e的时候,输入框会把e当成一个数字看待。

    可以采用下面的方式来避免这个BUG,在input标签中添加如下属性:

    onKeypress=“return(/[\d.]/.test(String.fromCharCode(event.keyCode)))”

    <el-input placeholder="请输入密码" v-model="input" :show-password="true"></el-input>

    show-password 加上这个属性输入字符进行隐藏一般用于密码框使用

    记录问题!

    以上这篇vue 限制input只能输入正数的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持站长博客。

    jsjbwy
    下一篇:没有了