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

Vue文本输入框自动补前导零:解决watch监听失效问题

原watch方案的问题在于,选中输入框内容替换输入时,虽逻辑上会触发补零,但受Vue响应式更新时机或光标位置影响,可能出现视觉上未生效的情况,且未做无效字符过滤,易输入非数字内容。

推荐用input事件直接处理输入,既及时又能优化体验:

<template>
  <input type="text" v-model="day" @input="handleDayInput" maxlength="2" />
</template>

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

const day = ref('');

const handleDayInput = (e) => {
  // 只保留数字,最多截取两位
  const validNum = e.target.value.replace(/\D/g, '').slice(0, 2);
  // 补前导零到两位
  const formattedVal = validNum.padStart(2, '0');
  
  // 记录当前光标位置,避免更新值后光标跳走
  const cursorPos = e.target.selectionStart;
  
  day.value = formattedVal;
  
  // 下一轮DOM更新后恢复光标位置
  nextTick(() => {
    e.target.setSelectionRange(cursorPos, cursorPos);
  });
};
</script>

如果一定要用watch,可加上同步触发配置,同时补全过滤逻辑:

import { ref, watch } from 'vue';

const day = ref('');

watch(day, (newVal) => {
  const validNum = newVal.replace(/\D/g, '').slice(0, 2);
  day.value = validNum.padStart(2, '0');
}, { flush: 'sync' });

注意:watch方案会导致光标自动跳到输入框开头,体验不如input事件方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:22:42