vue3 | 验证码框 | 自动获取焦点实现连续输入 | 组合式api

431 阅读1分钟

原生vue3四位数验证码框实现

效果图

1439_1724582848(原视频)_converted.gif

demo

 <div class="verification-container">
    <input
      v-for="(code, index) in verificationCodes"
      :key="index"
      v-model="verificationCodes[index]"
      @input="handleInput(index, $event)"
      @keydown="handleKeyDown(index, $event)"
      maxlength="1"
      class="verification-input"
    />
</div>
// 验证码框
const verificationCodes = ref(['', '', '', ''])
const handleInput = (index, event) => {
  const value = event.target.value
  verificationCodes.value[index] = value

  // 自动跳到下一个输入框
  if (value && index < verificationCodes.value.length - 1) {
    const nextInput = event.target.nextElementSibling
    if (nextInput) {
      nextTick(() => {
        nextInput.focus()
      })
    }
  }
}
const handleKeyDown = (index, event) => {
  // 处理删除操作
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling
    if (prevInput) {
      nextTick(() => {
        prevInput.focus()
      })
    }
  }
}