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;
}
相关推荐
远之喵16 分钟前
js基础知识-考点
前端
如此风景17 分钟前
TS装饰器
前端
鱼樱前端18 分钟前
React完整学习指南:从入门到精通(从根class->本hooks)16-19完整对比
前端·react.js
紫琪软件工作室20 分钟前
ElementUI 级联选择器el-cascader启用选择任意一级选项,选中后关闭下拉框
前端·elementui·vue
思想永无止境20 分钟前
vue elementUI组件国际化
前端·vue.js·elementui
_Lok21 分钟前
Element Plus性能优化实战:从卡顿到流畅的进阶指南
前端
顾林海23 分钟前
Flutter Dart 面向对象编程全面解析
android·前端·flutter
前端卧龙人25 分钟前
如何用 TypeScript 的 keyof 实现类型安全的属性访问?
前端
LamBoring27 分钟前
前端工程化实战指南:从框架搭建到性能优化
前端
谦谦橘子28 分钟前
preact原理解析
前端·javascript·preact