Element Plus 中 el-input 限制为数值输入的方法

方法一:使用 type="number"

javascript 复制代码
<template>
  <el-input v-model="numberValue" type="number" />
</template>

<script setup>
import { ref } from 'vue';

const numberValue = ref('');
</script>

方法二:使用自定义指令过滤非数字

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

<script setup>
import { ref } from 'vue';

const numberValue = ref('');

// 自定义指令
const vNumberOnly = {
  mounted(el) {
    el.querySelector('input').addEventListener('input', (e) => {
      e.target.value = e.target.value.replace(/[^\d]/g, '');
    });
  }
};
</script>

方法三:使用 onInput 事件处理

javascript 复制代码
<template>
  <el-input 
    v-model="numberValue" 
    @input="handleNumberInput"
    placeholder="只能输入数字"
  />
</template>

<script setup>
import { ref } from 'vue';

const numberValue = ref('');

const handleNumberInput = (value) => {
  numberValue.value = value.replace(/[^\d]/g, '');
};
</script>
相关推荐
li35741 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj2 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel2 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel2 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
^Rocky3 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵3 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld3 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
笑鸿的学习笔记4 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
东风西巷5 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求