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

Vue项目金额输入框格式化异常:输入字符残留问题求助

解决Vue金额输入框字符残留问题

你的核心问题是没有阻止键盘事件的默认输入行为,导致手动更新price后,浏览器仍会将输入的字符添加到输入框,和v-model的更新产生冲突,最终出现字符残留。

修复方案

在处理完价格格式化逻辑后,调用event.preventDefault()阻止默认的字符输入行为,同时优化价格补0逻辑(用padStart替代硬拼接0,更健壮):

new Vue({
  el: '#app',
  data: {
    price: '00.00'
  },
  methods: {
    handleKeyDown(event) {
      const key = event.key;
      const validKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

      // 过滤非数字键
      if (!validKeys.includes(key)) {
        event.preventDefault();
        return;
      }

      // 拼接新数字串(去掉小数点)
      const newPriceStr = this.price.replace('.', '') + key;
      const parsedPrice = parseInt(newPriceStr, 10); // 用parseInt更适配整数处理

      // 限制最大值(9999对应99.99)
      if (isNaN(parsedPrice) || parsedPrice > 9999) {
        event.preventDefault();
        return;
      }

      // 格式化带小数点的金额,补0到5位(如0.01→00.01,1.42→01.42)
      const priceWithDecimal = (parsedPrice / 100).toFixed(2);
      this.price = priceWithDecimal.padStart(5, '0');

      // 关键:阻止默认输入动作,避免字符残留
      event.preventDefault();
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

<div id="app">
  <input type="text" v-model="price" @keydown="handleKeyDown">
</div>

关键说明

  1. 阻止默认行为:event.preventDefault()会取消浏览器默认的字符输入动作,让输入框内容完全由price变量控制,从根源解决字符残留问题。
  2. 优化补0逻辑:padStart(5, '0')自动在金额字符串前补0,确保始终是XX.XX的5位格式,比硬拼接"0"+...更灵活(比如处理99.99时不会变成099.99)。
  3. 整数处理优化:用parseInt替代parseFloat处理数字串,避免不必要的浮点运算问题。

额外建议

如果需要支持粘贴输入等场景,可以额外监听@input事件,在输入后重新格式化金额,确保内容始终符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:57:54