vue通过指令限制input输入框只能输入数字,通过修饰符控制可限制仅输入正数、小数点位数、自动补零

一、效果

二、指令封装

js 复制代码
/**
 * 使用 v-only-number.positive.full="3"
 * 
 *    ="3" 表示允许输入小数,小数位数最多3位,默认为0
 *    positive 表示只能输入正数
 *    full 表示自动补零。前提是允许输入小数,否则不要写full修饰符
 * 
 */

Vue.directive('only-number', {
  bind: function (el, {
    value = 0,
    modifiers
  }) {
    el = el.nodeName == "INPUT" ? el : el.children[0]
    const RegStr = value == 0 ? `^[\\+\\-]?\\d+\\d{0,0}` : `^[\\+\\-]?\\d+\\.?\\d{0,${value}}`;
    el.addEventListener('keyup', function () {
      if (el.value != '-') {
        el.value = el.value.match(new RegExp(RegStr, 'g'));
        if (modifiers.positive) {
          el.value = el.value.replace('-', '')
        }
        el.dispatchEvent(new Event('input'))
      }
    })
    el.addEventListener('blur', function () {
      let num = el.value.match(new RegExp(RegStr, 'g')) || '0.00';
      // 自动补零
      if (modifiers.fill) {
        let str = num.toString()
        let decimalPosition = str.indexOf('.')
        if (decimalPosition < 0) {
          decimalPosition = str.length
          str += '.'
        }
        while (str.length <= (decimalPosition + Number(value))) {
          str += '0'
        }
        num = str
        el.value = num
      }
      if (modifiers.positive) {
        el.value = el.value.replace('-', '')
      }
      el.dispatchEvent(new Event('input'))
    })
  }
})

三、使用

js 复制代码
<el-input v-model="inputValue" v-only-number.fill.positive="3" clearable></el-input>
相关推荐
!win !2 小时前
前端跨标签页通信方案(下)
前端·javascript
f***45322 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
编码追梦人2 小时前
从 “手忙脚乱“ 到 “行云流水“:华为云 DevUI 与 MateChat 如何让前端开发飞起来
前端·华为云
S***H2833 小时前
前端动画实现经验,性能优化与兼容性
前端
xw53 小时前
前端跨标签页通信方案(下)
前端·javascript
zzlyx994 小时前
IoTSharp前端VUE采用npm run build编译提示require() of ES Module 出错
前端·vue.js·npm
全栈技术负责人4 小时前
拒绝“无法复现”:前端全链路日志排查实战手册
前端·全链路·问题排查思路
加洛斯4 小时前
前端小知识003:JS中 == 与 === 的区别
开发语言·前端·javascript
b***9104 小时前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
android·前端·后端·mybatis
G***E3164 小时前
前端路由懒加载实现,Vue Router与React Router
前端·vue.js·react.js