实现重发验证码的等待时间不随页面刷新关闭消失,真正的做到

我们可以用到 cookie ,把发送验证码的倒计时写入到cookie 里面,每次在页面初始化的时候都读取有就获取没有就写入

const currentTime = 60 //默认等待的时间
export default {

  data() {
    return {
      code: '', // 验证码
      time: currentTime, // 剩余时间
      timer: null // 定时器
    }
  },
  mounted() {
    // 获取cookie的验证码时间
    this.getCodeHasTime()
  },
  methods: {
    // 发送验证码的方法
    async gotoSendCode() {
      // 设置时间
      this.setTimeCookie()
      // 请求验证码
      // TODO
    },
    // 获取最新的cookie的时间
    getCodeTime() {
      const oldTime = Cookies.get('codeTime')
      if (oldTime) {
        const remainTime =
          currentTime -
          new Date(escape(new Date().getTime()) - oldTime).getSeconds()
        this.setTimer(remainTime)
      }
    },
    setTimeCookie() {
      Cookies.set(`codeTime`, escape(new Date().getTime()), {
        expires: (currentTime * 1) / (24 * 60 * 60),
        domain: '.jdcloud.com'
      })
      Cookies.set(`codeTime`, escape(new Date().getTime()), {
        expires: (currentTime * 1) / (24 * 60 * 60),
        domain: '.jcloud.com'
      })
      this.setTimer(currentTime)
    },
    setTimer(val) {
      this.time = val
      this.isSendCode = true
      this.timer = setInterval(() => {
        if (this.time > 0) {
          this.time--
        } else {
          clearInterval(this.timer)
          this.time = currentTime
          this.isSendCode = false
        }
      }, 1000)
    }
  }
}

本文来自博客园,作者:我爱小番茄,转载请注明原文链接:https://www.cnblogs.com/l-y-c/p/12621111.html

原文地址:https://www.cnblogs.com/l-y-c/p/12621111.html