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>
相关推荐
我不只是切图仔28 分钟前
我只是想给网站加个注册验证码,咋就那么难!
前端·后端
该用户已不存在1 小时前
macOS是开发的终极进化版吗?
前端·后端
小豆包api1 小时前
小豆包AI API × Nano Banana:3D手办 + AI视频生成,「动起来」的神级玩法!
前端·api
布列瑟农的星空2 小时前
大话设计模式——观察者模式和发布/订阅模式的区别
前端·后端·架构
龙在天2 小时前
Vue3 实现 B站 视差 动画
前端
KenXu2 小时前
F2C Prompt to Design、AI 驱动的设计革命
前端
小鱼儿亮亮2 小时前
canvas中画线条,线条效果比预期宽1像素且模糊问题分析及解决方案
前端·react.js
@大迁世界2 小时前
用 popover=“hint“ 打造友好的 HTML 提示:一招让界面更“懂人”
开发语言·前端·javascript·css·html
伍哥的传说2 小时前
Tailwind CSS v4 终极指南:体验 Rust 驱动的闪电般性能与现代化 CSS 工作流
前端·css·rust·tailwindcss·tailwind css v4·lightning css·utility-first
小鱼儿亮亮2 小时前
使用Redux的combineReducers对数据拆分
前端·react.js