Vue3实现6位验证码输入框,用户可以连续输入和删除

2023-12-13 22:48:33

Vue3实现6位验证码输入框,用户可以连续输入和删除

在这里插入图片描述

<!--
 * @Author: aili
 * @Date: 2023-10-24 14:18:05
 * @LastEditTime: 2023-12-6 22:58:21
 * @LastEditors: aili
 * @Description: code输入框
 * @FilePath: /web/src/views/Register/components/CodeInput.vue
 * @version: 
-->
<template>
    <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>
  </template>
  <script setup>
  import { ref, defineEmits, nextTick } from 'vue';
  const emits = defineEmits(['emailCode']);
  const verificationCodes = ref(['', '', '', '', '', '']);
   
  const handleInput = (index, event) => {
    const value = event.target.value;
    verificationCodes.value[index] = value;
   
    // 判断是否输入完成
    if (verificationCodes.value.join('').length === 6) {
      emits('emailCode', verificationCodes.value.join(''));
    }
   
    // 自动跳到下一个输入框
    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();
        });
      }
    }
  };
  </script>
  <style lang="scss" scoped>
  .verification-container {
    display: flex;
  }
   
  .verification-input {
    width: 45px;
    height: 45px;
    margin-right: 15px;
    text-align: center;
    font-size: 20px;
    border: 1px solid #ebebeb;
    border-radius: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
   
  .verification-input:focus {
    outline: none;
    // border-color: #007bff;
    // box-shadow: 0 0 5px #007bff;
  }
  </style>

文章来源:https://blog.csdn.net/IT13333/article/details/134843657
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。