在某些项目中 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;
  }

2022/4/29 新增,只允许输入正常数组 比如 1 1.02 -2

numberOnly: {
      bind: function(el) {
        el.handler = function() {
          // el.value = Number(el.value.replace(/\D+/, ''))
          const t = el.value.charAt(0)
          // 转化为数字形式--包含小数,负数
          // 先把非数字的都替换掉,除了数字和.
          el.value = el.value.replace(/[^\d.]/g, '')
          // 必须保证第一个为数字而不是.
          el.value = el.value.replace(/^\./g, '')
          // 保证只有出现一个.而没有多个.
          el.value = el.value.replace(/\.{2,}/g, '.')
          // 保证.只出现一次,而不能出现两次以上
          el.value = el.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
          // 如果第一位是负号,则允许添加
          if (t === '-') {
            el.value = '-' + el.value
          }
          return el.value
        }
        el.addEventListener('input', el.handler)
      },
      unbind: function(el) {
        el.removeEventListener('input', el.handler)
      }
    }

比上面自定义指令更方便的 只能输入纯正数:

   <a-input oninput="value=value.replace(/[^\d]/g,'')" v-model="form.scoreMin"  />

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐