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;
}
相关推荐
IT_陈寒12 分钟前
为什么你应该学习React?
前端·人工智能·后端
ZoeLandia13 分钟前
React04:事件处理与受控表单
开发语言·前端·react.js·typescript
亿元程序员17 分钟前
用AI做了一款微信小游戏,却发现上传不了
前端
Ai-_Man21 分钟前
我需要批量导出Poe左边栏所有对话,而不是一条具体的对话内容,你们AI导出鸭可以吗?
开发语言·前端·javascript·人工智能·小程序
java1234_小锋23 分钟前
【技术专题】HTML5 网页技术 - Web Storage 本地存储 & 文件 API & 拖放 API
前端·html·html5
恋猫de小郭24 分钟前
Flutter 官方表示:AI 时代代码越来越容易写,为什么还要一套代码库?
android·前端·flutter
软件派31 分钟前
Chrome 插件开发实战指南
前端·chrome
ly768931 分钟前
性能剖析与压测方法论:JMH、async-profiler 与分层瓶颈定位的可复现实验
服务器·前端·数据库·压测·jmh·性能剖析·async-profiler
ZoeLandia44 分钟前
React05:useEffect 与副作用
开发语言·前端·react.js·typescript
狮子座的男孩1 小时前
html+css基础:24、2D变换(位移/缩放/旋转/扭曲(了解)/多重变换/变换原点)
前端·css·经验分享·html·2d位移·原点变换·缩放/旋转/扭曲