小程序:ios短信验证码自动粘贴填充了两次

2,070 阅读1分钟

大家都知道ios发送短信验证码的时候会自动读取验证码到粘贴板,我们可以直接粘贴这个验证码到input。不知道大家有没有遇到过验证码粘贴的时候会粘贴两次,就会导致第一次验证成功,第二次验证失败(验证码失效)。

我的解决方案是,加锁防止第二次粘贴的时候走验证逻辑

<input
    maxlength="4"
    bindinput="inputCode"
    class="ipt-opacity"
    focus="{{focus}}"
    type="number"
/>
// 监听input的输入
inputCode(e) {
    const val = e.detail.value;
    const code = val.split('');
    this.code = code;
    if (code.length === 4 && this.flag) { // flag为true的时候,是验证码第一次填充
      this.flag = false;// 填充之后flag置为false,再次填充的时候就不会继续往下走了
      user.login({ code: this.code.join(''), mobile: this.number }).then(() => {
        this.flag = true;
        this.$router.push('index', { openType: 'redirect' });
      }).catch(() => {
        this.flag = true;
      });
    }
}

ps:加锁可能比较暴力,大家如果有更好的方案欢迎评论分享