vue3 前端验证码-删除最后一个,焦点聚焦在前一个值上,并不会删除值

删除最后一个数字,焦点聚焦在前一个值上,并不会删除值

复制代码
<input
                v-for="(box, index) in boxes"
                :key="index"
                ref="inputRefs"
                :value="box"
                @input="onInputChange(index)"
                @keyup="onKeyDown($event, index)"
                :class="{ focused: box === '' && focusedIndex === index }"
                :maxlength="1"
                type="tel"
                autocomplete="off"
              />
            </div>

逻辑:

javascript 复制代码
const boxes = ref(['', '', '', '', '', '']);
const inputRefs = ref([]);
const errorMessage = ref('');
const focusedIndex = ref(0);
const onInputChange = (index) => {
  boxes.value[index] = inputRefs.value[index].value;
  if (inputRefs.value[index].value.length > 0 && index < 5) {
    inputRefs.value[index + 1].focus();
    inputRefs.value[index + 1].select();
  }
};

const onKeyDown = (event, index) => {
  if (event.key === 'Backspace') {
    if (index > 0) { // 确保当前输入框不是第一个输入框
      boxes.value[index] = ''; // 清空当前输入框的值
      inputRefs.value[index - 1].focus(); // 将焦点移至上一个输入框
    }
  }
};

const verifyCode = computed(() => {
  return boxes.value.join(''); //要提交给后台的6位数字
});

const validateCode = () => {
  if (verifyCode.value.length !== 6) {
    errorMessage.value = '请输入6位验证码';
  } else {
    errorMessage.value = '';
  }
  return verifyCode.value.length === 6;
};

watch(verifyCode, (newValue) => {
  if (newValue.length === 6) {
    validateCode();
  }
});


onMounted(() => {
  nextTick(() => {
    inputRefs.value[0].focus();
  });
})

样式:

css 复制代码
.code-inputs {
  display: flex;
  gap: 5px;
}

.code-inputs input {
  width: 40px;
  height: 40px;
  text-align: center;
  border: 1px solid #ccc;
}

.focused {
  border-color: blue;
}
相关推荐
恋猫de小郭13 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅20 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606121 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了21 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅21 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅21 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅1 天前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment1 天前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅1 天前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊1 天前
jwt介绍
前端