一、验证码输入框的原理
验证码的实现分两部分,一上层的input框,二下层的验证码框样式展示。我们要实现以下图片效果。
二、验证码输入框的实现
- 初始化codeArr数组,根据自定义的inputLength输入数量,创建具有inputLength数组长度,每项为对象包含初始num,focusFlag的数组。
restCode(){
this.codeArr = Array.from({
length: this.inputLength
}, () => ({
num: '',
focusFlag: false
}));
}
- 根据数组的内容,for循环出验证码输入框的样式。
<view class="block-list">
<block v-for="(item,index) in codeArr">
<view class="block" :class="inputIndex==index?'filcker':''">{{item.num}}</view>
</block>
</view>
- 通过输入框的@input监听方法,获取inputValue的值,通过第一步的方法,重置codeArr数组。将inputValue值拆分成数组strArr,将strArr数组值赋值给codeArr数组。
inputNum(e) {
this.inputValue = e.detail.value;
this.restCode();
let strArr = Array.from(this.inputValue);
strArr.forEach((item, index) => {
this.codeArr[index].num = Number(item);
})
}
- 通过inputIndex判断验证码框的焦点闪烁位置。通过watch监视inputValue值,当新值大于旧值,说明正在输入;当新值小于旧值,说明正在删除。将新值赋值给inputIndex,实现了验证码焦点的移动显示。
watch: {
inputValue(newValue, oldValue) {
console.log('123', newValue, oldValue);
if (newValue > oldValue) {
this.toward = 'front';
this.inputIndex = newValue.length
console.log('向前', this.inputIndex);
} else {
this.toward = 'behind';
this.inputIndex = newValue.length
console.log('向后', this.inputIndex);
}
}
}
- 将input定位到验证码输入框的上方,设为透明。input长度绑定inputLength设置长度,开启默认获取焦点。
三、总结
此时我们的验证码就制作完成。需要查看完整代码可查看下方代码git仓库自行学习。