Vue + ElementPlus 自定义指令控制输入框只可以输入数字

自定义指令 v-number-only

1. 创建指令文件

src/directives/numberOnly.ts

ts 复制代码
/**
 * 自定义指令
 * @description 输入框只允许输入数字
 * @example
 * <el-input v-model="num" v-number-only placeholder="只能输入数字" />
 */
import type { Directive } from 'vue'

export const numberOnly: Directive<HTMLInputElement> = {
  mounted(el) {
    const input = el.querySelector('input')!
    input.addEventListener('input', () => {
      // 使用正则替换掉所有非数字字符
      input.value = input.value.replace(/\D/g, '')
      // 触发 v-model 更新
      input.dispatchEvent(new Event('input'))
    })
  }
}

2. 注册指令

main.ts 中注册全局指令:

ts 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import { numberOnly } from './directives/numberOnly'

const app = createApp(App)

app.directive('number-only', numberOnly)

app.mount('#app')

3. 使用方式

在任何 el-input 上都可以直接使用:

vue 复制代码
<template>
  <el-input v-model="num" v-number-only placeholder="只能输入数字" />
</template>

<script setup lang="ts">
import { ref } from 'vue'

const num = ref('')
</script>

拓展

支持数字 + 小数点 + 负号

ts 复制代码
/**
 * 数字 + 小数点 + 负号
 */
export const numberWithDecimal: Directive<HTMLInputElement> = {
  mounted(el) {
    const input = el.querySelector('input')!
    input.addEventListener('input', () => {
      let val = input.value
      // 允许开头负号
      val = val.replace(/[^0-9.-]/g, '')
      // 只允许一个负号(且必须在开头)
      val = val.replace(/(?!^)-/g, '')
      // 只允许一个小数点
      val = val.replace(/(\..*)\./g, '$1')

      input.value = val
      input.dispatchEvent(new Event('input'))
    })
  }
}

支持千分位格式化

ts 复制代码
/**
 * 千分位格式化(只允许数字)
 * 输入 1234567 -> 显示 1,234,567
 */
export const numberThousands: Directive<HTMLInputElement> = {
  mounted(el) {
    const input = el.querySelector('input')!
    input.addEventListener('input', () => {
      // 去掉所有非数字
      let raw = input.value.replace(/\D/g, '')
      if (!raw) {
        input.value = ''
      } else {
        // 格式化成千分位
        input.value = Number(raw).toLocaleString()
      }
      input.dispatchEvent(new Event('input'))
    })
  }
}

只允许输入中文

ts 复制代码
/**
 * 只允许输入中文
 */
export const chineseOnly: Directive<HTMLInputElement> = {
  mounted(el) {
    const input = el.querySelector('input')!
    input.addEventListener('input', () => {
      // 过滤掉所有非中文字符(\u4e00-\u9fa5 是中文字符范围)
      input.value = input.value.replace(/[^\u4e00-\u9fa5]/g, '')
      input.dispatchEvent(new Event('input'))
    })
  }
}
相关推荐
RickyWasYoung37 分钟前
【matlab】字符串数组 转 double
android·java·javascript
csj501 小时前
前端基础之《React(4)—webpack简介-编译打包优化》
前端·react
万少1 小时前
Trae AI 编辑器6大使用规则
前端·javascript·人工智能
好玩的Matlab(NCEPU)1 小时前
如何编写 Chrome 插件(Chrome Extension)
前端·chrome
Yan-英杰2 小时前
Deepseek大模型结合Chrome搜索爬取2025AI投资趋势数据
前端·chrome
Crystal3282 小时前
app里video层级最高导致全屏视频上的操作的东西显示不出来的问题
前端·vue.js
weixin_445476682 小时前
Vue+redis全局添加水印解决方案
前端·vue.js·redis
lecepin2 小时前
AI Coding 资讯 2025-10-29
前端·后端·面试
余道各努力,千里自同风2 小时前
小程序中获取元素节点
前端·小程序
PineappleCoder2 小时前
大模型也栽跟头的 Promise 题!来挑战一下?
前端·面试·promise