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'))
    })
  }
}
相关推荐
和平宇宙18 分钟前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记
IT_陈寒32 分钟前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
naildingding1 小时前
3-ts接口 Interface
前端·typescript
mONESY1 小时前
JavaScript 栈、队列、数组与链表核心知识点总结
javascript·面试
小小前端仔LC1 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端
ZengLiangYi1 小时前
TypeScript 项目配置:tsconfig、ESM、路径别名
javascript·typescript·aigc
晓13131 小时前
【Cocos Creator 3.x】篇——第二章 入门
前端·javascript·游戏引擎
想要成为糕糕手1 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
程序员黑豆2 小时前
AI全栈开发之Java:怎么配置Java环境变量
前端·后端·ai编程
xiaofeichaichai2 小时前
React Hooks
前端·javascript·react.js