uniapp中如何基于vue3實現(xiàn)輸入驗證碼功能
實現(xiàn)效果

描述
使用uniapp和vue3實現(xiàn)了手機獲取驗證碼后,輸入驗證碼的輸入框功能
具體實現(xiàn)代碼
下述代碼為實現(xiàn)驗證碼輸入框封裝的組件VerificationCodeInput.vue
<template>
<view class="container">
<view class="input-container">
<view v-for="index in 4" :key="index" class="verify-input">
<input
type="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)
// 輸入值數(shù)組
const values = ref<string[]>(['', '', '', ''])
// 輸入框ref數(shù)組
const inputRefs = ref<(HTMLInputElement | null)[]>([])
/**
* 處理每個輸入值函數(shù)
* @param index - 序號.
* @param event - 輸入事件對象.
*/
const handleInput = (index: number, event: Event) => {
// 獲取輸入框的值
const input = event.target as HTMLInputElement
const value = input.value
if (value) {
// 更新輸入值數(shù)組
values.value[index] = value
// 判斷是否還有下一個輸入框,如果有則聚焦
if (index < 3) {
nextTick(() => {
focusIndex.value = index + 1
const nextInput = inputRefs.value[index + 1]
nextInput?.focus()
})
}
// 判斷是否所有輸入框都已經(jīng)有值,如果有則觸發(fā)完成事件
if (values.value.every((v) => v.length > 0)) {
handleComplete()
}
} else {
// 如果輸入值為空,則聚焦前一個輸入框
if (index > 0) {
focusIndex.value = index - 1
nextTick(() => {
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即可實現(xiàn)上圖效果

到此這篇關(guān)于uniapp中基于vue3實現(xiàn)輸入驗證碼功能的文章就介紹到這了,更多相關(guān)vue3輸入驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中$set的使用(結(jié)合在實際應(yīng)用中遇到的坑)
這篇文章主要介紹了vue中$set的使用(結(jié)合在實際應(yīng)用中遇到的坑),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Vue使用openlayers實現(xiàn)繪制圓形和多邊形
這篇文章主要為大家詳細介紹了Vue如何使用openlayers實現(xiàn)繪制圓形和多邊形,文中的示例代碼講解詳細,感興趣的小伙伴快跟隨小編一起動手嘗試一下2022-06-06
Vue?中?Promise?的then方法異步使用及async/await?異步使用總結(jié)
then?方法是?Promise?中?處理的是異步調(diào)用,異步調(diào)用是非阻塞式的,在調(diào)用的時候并不知道它什么時候結(jié)束,也就不會等到他返回一個有效數(shù)據(jù)之后再進行下一步處理,這篇文章主要介紹了Vue?中?Promise?的then方法異步使用及async/await?異步使用總結(jié),需要的朋友可以參考下2023-01-01
vue+element?DatePicker實現(xiàn)日期選擇器封裝
Vue?Element?DatePicker是一款基于Vue.js的日期選擇控件,它提供了豐富的日期選擇功能,支持日期范圍選擇、日期格式化、自定義日期格式、快捷選擇等功能,極大地提高了用戶的體驗,是開發(fā)者必備的日期選擇控件。2023-02-02

