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

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>
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值