vue 限制input只能输入正数

在某些项目中 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"  />

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值