发送验证码倒计时 防刷新重置!!!
需求:发送验证码,每60s可点击发送一次,倒计时中按钮不可点击,且刷新页面倒计时不会重置
可用以下方式避免刷新页面时,倒计时重置
localStorage本地缓存方式
思路:
1.记录倒计时的时间
2.页面加载时(刷新页面时)先获取存储的时间
3.判断存储的时间,
不存在则正常初始化;
大于1则将存储的时间数字赋值给时间变量继续执行倒计时;
小于1则正常初始化
<button @click="getCode">{{timeText}}</span>data(){return {timeText: '获取验证码',canSend: true, //是否可发送验证码time: 60, }
}methods: {getCode(){this.handleCountDownTime()},//处理倒计时 和 按钮点击状态handleCountDownTime(){let timer = setInterval(() => {if (this.time > 1 && this.time <= 60) {this.time = this.time - 1this.canSend = falsethis.timeText = `${this.time} s后获取`//每次刷新纪录一次 倒计时的时间localStorage.setItem('countDownTime',new Date().getTime())} else {this.time = 60this.canSend = truethis.timeText = `获取验证码`clearInterval(timer)localStorage.removeItem('countDownTime')}}, 1000)}
},created(){let countDownTime = localStorage.getItem('countDownTime')if(countDownTime && countDownTime > 1){this.time = countDownTime //剩下的需要计时的秒数this.handleCountDownTime()}
}