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>
相关推荐
用户214965158987525 分钟前
从零搭建uniapp环境-记录
前端
努力写代码的熊大2 小时前
stack、queue与priority_queue的用法解析与模拟实现
java·前端·javascript
im_AMBER2 小时前
React 06
前端·javascript·笔记·学习·react.js·前端框架
wyzqhhhh2 小时前
前端常见的设计模式
前端·设计模式
IT_陈寒3 小时前
React 19重磅前瞻:10个性能优化技巧让你少写30%的useEffect代码
前端·人工智能·后端
今天没有盐4 小时前
💕CSS 基础入门指南💕:选择器与文本样式
前端·html·响应式设计
云枫晖4 小时前
Webpack系列-Entry入口
前端·webpack
mustfeng4 小时前
VCS & Verdi 2023安装
java·服务器·前端
Mintopia4 小时前
🌐 数据合规框架下的 WebAIGC 训练数据处理技术规范
前端·javascript·aigc
骥龙5 小时前
2.6、Web漏洞挖掘实战(下):XSS、文件上传与逻辑漏洞深度解析
前端·xss