2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 微信小程序 - 实现验证码组件

微信小程序 - 实现验证码组件

时间:2023-03-10 02:34:40

相关推荐

微信小程序 - 实现验证码组件

前言

之前用vue写过一篇验证码组件的文章,现在用微信小程序实现。

布局

vue中的布局相同,换成小程序的写法:

<view class="ys-verification"><view class="input-wrapper" wx:for="{{amount}}" wx:key="index"><input type="number" value="{{code[index]}}" data-index="{{item}}" title="code" focus="{{item === currentIndex}}" maxlength="1" bindinput='handleInput'/></view></view>

样式

/* components/VerificationCodeInput/verificationCodeInput.wxss */.ys-verification {width: 100%;height: 80px;display: flex;justify-content: space-around;}.ys-verification .input-wrapper {border-bottom: 1px solid #d6d6d6;width: 15%;height: 0;padding-bottom: 20%;position: relative;}.ys-verification input {position: absolute;width: 100%;height: 100%;text-align: center;transition: all 0.3s;font-size: 7vw;color: #333;}.ys-verification input:focus {border-bottom: 1px solid #666;}

聚焦

利用input的focus属性绑定data中的currentIndex变量,可以实现input随输入的进行而移动的效果。

删除

利用data中储存的code值与输入的值相比较判断是否有删除操作,但是这样的缺点是:没办法在当前输入框为空的情况下判断是否进行了删除操作。

组件method

handleInput(e){let value = this.validateNumber(e.detail.value);let index = e.currentTarget.dataset.index;const oldValue = this.data.code[index];if(value!==''){let code = this.data.code;code[index] = value;this.setData({code,currentIndex: ++index});if(!code.includes('')){this.triggerEvent('onCompleted',{code: code.join('')},{bubbles: true,composed: true})}}else{const isDeleted = oldValue !== ''; // 但是无法监听当value为''的情况,因为不会触发input事件-->let code = this.data.code;code[index] = '';this.setData({code,currentIndex: isDeleted?--index:index})}},validateNumber(val) {return val.replace(/\D/g, '')},}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。