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;
}
相关推荐
zzzzzz3102 小时前
别急着把动效组件搬进页面:从 react-bits 看 React 动效库该怎么评估
前端·react.js·开源
李姆斯9 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
鱼与宇11 小时前
前端Web(html+css+js+vue3)
前端
孙克旭_12 小时前
Docker 镜像构建|Vue+SpringBoot+Go 多语言项目 Dockerfile 案例
linux·运维·vue.js·spring boot·docker·dockerfile
雪芽蓝域zzs13 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
研☆香13 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
东风破_13 小时前
JWT 1:从一个登录请求开始,理解 React 项目里的 API 层与 Mock
前端·后端
东风破_14 小时前
JWT 3:为什么 Token 要放进 Authorization?Axios 拦截器到底解决了什么?
前端·后端
东风破_14 小时前
JWT 5:路由守卫是什么?把整个 JWT 登录鉴权流程串起来
前端·后端
东风破_14 小时前
JWT 2:HTTP 是无状态的,为什么登录成功后还要给 Token?
前端·后端