手机发送验证码计时后切换app后在切回来并没有更新计时的问题

30 篇文章 0 订阅

使用的是vue框架,写了发送验证码功能,后来发现发送验证码后假如剩余40s, 切出去换页面回来还剩40s,就离谱,后来就打算使用缓存来做这个处理了

重点部分的代码我是用注释标注出来

    // 发送验证码
    async sendCode(newKeyCode = undefined) {
      if (!this.isSendCodeActive) {
        return;
      }
      this.sendCodeLoaing = true;
      if (!this.globalProcessData.getPublicKey() && !newKeyCode) {
        // 没有publicKeyCode,重新获取
        this.rsaFailure();
        return;
      }

      const params = {
        data: {
          mobile: this.codeForm.phoneNum,
        },
      };
      // 将data数据加密并封装为request再请求接口
      const request = this.$loginUtils.handleEncryptionRequest(
        params,
        // 如果公钥不存在则使用刷新的公钥
        newKeyCode || this.globalProcessData.getPublicKey()
      );
      const response = await sendAuthCode(request).catch(() => {});
      if (response.code !== 0) {
        this.$message({
          message: response.msg,
          type: 'error',
        });
        this.sendCodeLoaing = false;
        return;
      }
      if (this.timeObj.codeCount) {
        clearTimeout(this.timeObj.codeCount);
      }
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      window.sessionStorage.setItem(
        'time_' + location.href,
        new Date().getTime()
      );
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      this.countDownFn(this.countDownNum);
      // this.countDownNum--;
    },
    // 倒计时
    countDownFn(time) {
      this.countDownNum = time;
      if (time === 0) {
        this.sendMsg = '重新发送';
        this.countDownNum = COUNT_DOWN_NUMBER;
        this.sendCodeLoaing = false;
        return;
      }
      this.countDownNum--;
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      // 当前时间
      const nowTime = new Date().getTime();
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      // 上次缓存时间
      const lastTime = window.sessionStorage.getItem('time_' + location.href);
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      // 两次时间差
      const diff = nowTime - lastTime / 1000;
      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      // 如果本地缓存有读秒,则使用本地缓存的读秒
      if (diff < 60) {
        this.countDownNum = 60 - diff;
      }
      this.sendMsg = `剩余${this.countDownNum}`;
      this.timeObj.codeCount = setTimeout(() => {
        this.countDownFn(this.countDownNum);
      }, 1000);
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值