vue获取验证码点击事件之后一分钟倒计时三种情况

本文详细介绍了在前端实现验证码获取后的倒计时机制,包括如何防止页面刷新导致计时器失效,通过Cookie和Session存储时间状态,以及与后端配合确保用户在限定时间内无法频繁获取验证码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简单加一个倒计时(刷新倒计时失效)
1、获取验证码的点击按钮

            <el-button :loading="loading" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable" type="primary" style="width: 25%;height:50px;text-align: center;float:right" @click.native.prevent="getCode">
              {{codeBtnWord}}
            </el-button>

2、在data return中赋默认值

      getCodeBtnDisable: false,
      codeBtnWord: '获取验证码', // 获取验证码按钮文字
      waitTime: 61, // 获取验证码按钮失效时间
            phone: {
        phone: '',
        code: ''
      }

3、获取验证码以及倒计时方法

    getCode() {
      console.log('验证码的方法')
      getCode(this.phone).then(res => {
        if (res.code === 0) {
          this.phoneTimer()
        }
      })
    },
    // 倒计时计时器方法
    phoneTimer() {
      const that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `${this.waitTime}s 后重新获取`
      console.log('获取时间的值2:' + this.waitTime)
      const timer = setInterval(function() {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `${that.waitTime}s 后重新获取`
        } else {
          clearInterval(timer)
          that.codeBtnWord = '获取验证码'
          that.getCodeBtnDisable = false
          that.waitTime = 61
        }
      }, 1000)
    },

二、将计时器写入cookie(防止页面刷新计时器失效)
1、按钮,初始值一致,只是方法不同
2、方法

    // 获取验证码
        getCode() {
      const timewait = this.$cookies.get(this.phone.phone)
      if (timewait !== undefined && timewait > 0) {
        this.waitTime = timewait
        this.phoneTimer()
      } else {
        this.$cookies.remove(this.phone.phone)
        console.log('验证码的方法')
        getCode(this.phone).then(res => {
          if (res.code === 0) {
            this.phoneTimer()
          }
        })
        this.phoneTimer()
      }

      // console.log('获取cookie的值:' + this.$cookies.get(this.phone.phone))
    },
    // 倒计时计时器方法
    phoneTimer() {
      // const millisecond = new Date().getTime()
      const that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `${this.waitTime}s 后重新获取`
      console.log('获取时间的值2:' + this.waitTime)
      const timer = setInterval(function() {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `${that.waitTime}s 后重新获取`
                   const expiresTime = new Date(millisecond + that.waitTime * 1000)
          this.$cookies.set(that.phone.phone, that.waitTime, { path: '/', expires: expiresTime })
        } else {
         this.$cookies.remove(this.phone.phone)
          clearInterval(timer)
          that.codeBtnWord = '获取验证码'
          that.getCodeBtnDisable = false
          that.waitTime = 61
        }
      }, 1000)
    },

此方法可以实现浏览器刷新防止计时器失效问题,但是更换浏览器计时器仍会失效,此时的cookie设置的过期时间只有页面关闭才会起效。
此方法的问题是:无论过是否超过一分钟计时器都会从你上一次刷新的时间接着计时。
解决上述问题思路:存入cookie的时候将value存入map值,map里面可以包含计时时间timer和当前时间戳,每次根据key获取value的时候取出存值的时间(上述所述当前时间戳)和你目前执行的当前时间戳对比判断是否超出一分钟,然后在进行判断,差值赋值等操作。
此思路未经验证,如有不足,欢迎指正一起学习进步。
三、配合后端实现,将时间存入session
1、vue方法

    getCode() {
      console.log('验证码的方法')
      getCode(this.phone).then(res => {
        if (res.code === 0) {
          this.phoneTimer()
        }
      })
    },
    // 倒计时计时器方法
    phoneTimer() {
      const that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `${this.waitTime}s 后重新获取`
      console.log('获取时间的值2:' + this.waitTime)
      const timer = setInterval(function() {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `${that.waitTime}s 后重新获取`
        } else {
          clearInterval(timer)
          that.codeBtnWord = '获取验证码'
          that.getCodeBtnDisable = false
          that.waitTime = 61
        }
      }, 1000)
    },

2、java后端代码

	@ResponseBody
	@RequestMapping(value = "/sys/getCode", method = RequestMethod.POST)
	public R getCode(String phone)throws IOException {
		Map map =  (Map)SecurityUtils.getSubject().getSession().getAttribute(phone);
		if(map != null){
			long a = Long.valueOf(String.valueOf(map.get("saveTime")));
			long b = System.currentTimeMillis();
			if((b-a) < 60 * 1000){
				return R.error("抱歉,不能频繁获取验证码");
			}
		}   
		    // 调用阿里云短信服务
            String a = PhoneCode.getPhonemsg(phone);

       return a.equals("true")? R.ok():R.error(a);
	}

3、java在调用阿里云短信成功后将生成的code验证码存入session

                Map map = new HashMap<>();
                long saveTime = System.currentTimeMillis();
                map.put("code",code);
                map.put("saveTime",saveTime);
                SecurityUtils.getSubject().getSession().setAttribute(mobile,map);
                // 请求成功
                System.out.println("获取验证码成功!!!"+code);

此方法我这只是简单的做了一个判断,如果在一分钟之内,就直接返回不能频繁请求的提示。
思路:如想页面继续使用计时器,则可以将当时code的存入时间与当前时间做对比,返回差值,vue端接收差值,赋给初始值继续调用计时器即可,(此思路未经验证)
借鉴:
https://www.cnblogs.com/belongs-to-qinghua/p/12071789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值