uniapp中如何基于vue3實現(xiàn)輸入驗證碼功能
更新時間:2024年09月12日 10:29:01 作者:deku-yzh
本文介紹了如何使用uniapp和vue3創(chuàng)建一個手機驗證碼輸入框組件,通過封裝VerificationCodeInput.vue組件,并在父組件中引入,可以實現(xiàn)驗證碼輸入功能,適合需要增加手機驗證碼驗證功能的開發(fā)者參考使用
實現(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)上圖效果

到此這篇關于uniapp中基于vue3實現(xiàn)輸入驗證碼功能的文章就介紹到這了,更多相關vue3輸入驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3中reactive的對象清空所引發(fā)的問題解決方案(清空不了和清空之后再去賦值就賦值不了)
在使用reactive定義的變量時,直接賦值會失去響應式,為了清空?filters并確保響應式,可以使用Object.assign({},?filters)或者遍歷對象逐個清除屬性,本文介紹vue3中reactive的對象清空所引發(fā)的問題解決方案(清空不了和清空之后再去賦值就賦值不了),感興趣的朋友一起看看吧2025-02-02
如何使用Vue mapState快捷獲取Vuex state多個值
這篇文章主要為大家介紹了如何使用Vue mapState快捷獲取Vuex state多個值實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
vue.js 打包時出現(xiàn)空白頁和路徑錯誤問題及解決方法
這篇文章主要介紹了vue.js 打包時出現(xiàn)空白頁和路徑錯誤問題及解決方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06

