You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2+Vuetify下移除数字输入框字母'e'的最优方案

最优解决方案

针对Vue 2 + Vuetify下禁止数字输入框输入字母'e'的需求,推荐两种场景化的最优实现方式:

1. 单输入框场景:使用@input事件实时过滤

直接在输入框上绑定input事件,实时移除输入内容中的'e'(不区分大小写),代码简洁且实时生效:

<v-text-field
  ref="Invoice"
  v-model="invoice"
  label="Invoice Number"
  required
  type="number"
  @input="filterInvalidChars"
></v-text-field>

在组件的methods中实现过滤逻辑:

methods: {
  filterInvalidChars(event) {
    // 移除所有'e'字符,如需同时禁止'-'可修改正则为 /[e-]/gi
    const filteredValue = event.target.value.replace(/e/gi, '');
    this.invoice = filteredValue;
  }
}

2. 多输入框复用场景:自定义指令

如果多个输入框都需要禁止输入'e',自定义指令可以避免重复代码,实现复用:

<template>
  <v-text-field
    ref="Invoice"
    v-model="invoice"
    label="Invoice Number"
    required
    type="number"
    v-disable-e
  ></v-text-field>
</template>

<script>
export default {
  directives: {
    // 自定义指令:禁止输入'e'
    'disable-e': {
      inserted(el) {
        // 获取Vuetify输入框内部的原生input元素
        const inputEl = el.querySelector('input');
        inputEl.addEventListener('input', function() {
          this.value = this.value.replace(/e/gi, '');
        });
      }
    }
  },
  data() {
    return {
      invoice: ''
    };
  }
};
</script>

注意事项

  • 保持type="number"可以保留数字输入框的原生特性(如上下箭头、移动端数字键盘);
  • 正则/e/gi会匹配大小写的'e',确保所有形式的'e'都被过滤;
  • 如需同时禁止负号'-',可将正则修改为/[e-]/gi。

内容的提问来源于stack exchange,提问作者Rolanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:30:56