删除最后一个数字,焦点聚焦在前一个值上,并不会删除值
<inputv-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>
逻辑:
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();});
})
样式:
.code-inputs {display: flex;gap: 5px;
}.code-inputs input {width: 40px;height: 40px;text-align: center;border: 1px solid #ccc;
}.focused {border-color: blue;
}