当前位置: 首页 > news >正文

uniapp中基于vue3实现输入验证码功能

实现效果
在这里插入图片描述
描述
使用uniapp和vue3实现了手机获取验证码后,输入验证码的输入框功能

具体实现代码
下述代码为实现验证码输入框封装的组件VerificationCodeInput.vue

<template><view class="container"><view class="input-container"><view v-for="index in 4" :key="index" class="verify-input"><inputtype="number"class="input-field":ref="`input${index - 1}`":maxlength="1":focus="focusIndex === index - 1"@input="handleInput(index - 1, $event)"@focus="handleFocus(index - 1)"/></view></view></view>
</template><script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'// 焦点索引
const focusIndex = ref(0)
// 输入值数组
const values = ref<string[]>(['', '', '', ''])
// 输入框ref数组
const inputRefs = ref<(HTMLInputElement | null)[]>([])/*** 处理每个输入值函数* @param index - 序号.* @param event - 输入事件对象.*/
const handleInput = (index: number, event: Event) => {// 获取输入框的值const input = event.target as HTMLInputElementconst value = input.valueif (value) {// 更新输入值数组values.value[index] = value// 判断是否还有下一个输入框,如果有则聚焦if (index < 3) {nextTick(() => {focusIndex.value = index + 1const nextInput = inputRefs.value[index + 1]nextInput?.focus()})}// 判断是否所有输入框都已经有值,如果有则触发完成事件if (values.value.every((v) => v.length > 0)) {handleComplete()}} else {// 如果输入值为空,则聚焦前一个输入框if (index > 0) {focusIndex.value = index - 1nextTick(() => {const prevInput = inputRefs.value[index - 1]prevInput?.focus()})}}
}// 处理焦点事件
const handleFocus = (index: number) => {focusIndex.value = index
}// 处理完成事件
const handleComplete = () => {const code = values.value.join('')console.log('验证码输入完成:', code)
}onMounted(() => {// 初始化焦点nextTick(() => {const firstInput = inputRefs.value[0]firstInput?.focus()})
})
</script><style>
.input-container {display: flex;justify-content: space-between;
}.verify-input {width: 60px;height: 60px;display: flex;justify-content: center;align-items: center;
}.input-field {width: 100%;height: 100%;text-align: center;font-size: 24px;border: none;border-bottom: 2px solid #ccc;outline: none;
}
</style>

最后在父组件中引入VerificationCodeInput.vue即可实现上图效果
在这里插入图片描述


http://www.mrgr.cn/news/24283.html

相关文章:

  • 问题:vite首次加载慢
  • OpenFeign
  • 原型模式详细介绍和代码实现
  • 一个简约的uniapp登录界面,基于uniapp+vue3+uview-plus
  • Vue3.5正式上线,有哪些新特性和用法?
  • Unity6的GPUDriven渲染到底是什么?
  • JavaScript高阶面试题:(第一天)
  • maven中的仓库的配置与优先级
  • 水平垂直居中的几种方法(总结)
  • 基于Spring Boot的电子请柬私人定制销售平台的设计与实现---附源码78900
  • 史级低价1元《魔域口袋版》神话斗神·黑悟空 带领战队傲视群雄
  • 住宅建筑电气火灾预防
  • electron有关mac构建
  • 【C语言进阶】C语言动态内存管理:深入理解malloc、calloc与realloc
  • 中国企业500强!最新名单揭晓→
  • 基于SpringBoot+Vue的考务管理系统
  • 【TCP】相关机制:异常处理
  • 多线程获取留言板
  • css总结(记录一下...)
  • Pycharm 输入三个引号没有自动生成函数(方法)注释