平时我们在项目中进行注册等的时候,会经常用到短信验证的功能,但是现在现在很多短信验证都是存在下面几个问题,例如短信验证时间为60s的时候,
1. 当点击完按钮时,倒计时还没到60s过完时,刷新浏览器,验证码按钮又可以重新点击
2.当点击按钮倒计时开始,例如在50s的时候我关闭了浏览器,过了5s后,我在打开,此时时间倒计时的时间应该是45s左右,但是当重新打开浏览器的时候,按钮又可以重新点击了
为了解决上面的两个问题,就需要把时间都写到localstorage里面去,当打开页面的时候,就去localstorage里面去取,我这里就贴上我的解决方法,因为前几天有个vue的项目用到该方法,所以我这里就写个vue的方法出来吧
组件里面的html代码:
<div class="mtui-cell__ft" @click="getCode"> <button class="mtui-vcode-btn mtui-text-center" v-if="flag">获取短信</button> <button class="mtui-vcode-btn mtui-text-center" v-if="!flag">剩余{{second}}s</button> </div>
重点来啦
在data里面定义几个需要用到的变量:
second: 60, flag: true, timer: null // 该变量是用来记录定时器的,防止点击的时候触发多个setInterval
获取短信验证的方法:
getCode() { let that = this; if (that.flag) { that.flag = false; let interval = window.setInterval(function() { that.setStorage(that.second); if (that.second-- <= 0) { that.second = 60; that.flag = true; window.clearInterval(interval); } }, 1000); } }
写入和读取localstorage:
setStorage(parm) { localStorage.setItem("dalay", parm); localStorage.setItem("_time", new Date().getTime()); }, getStorage() { let localDelay = {}; localDelay.delay = localStorage.getItem("dalay"); localDelay.sec = localStorage.getItem("_time"); return localDelay; }
防止页面刷新是验证码失效:
judgeCode() { let that = this; let localDelay = that.getStorage(); let secTime = parseInt( (new Date().getTime() - localDelay.sec) / 1000 ); console.log(localDelay); if (secTime > localDelay.delay) { that.flag = true; console.log("已过期"); } else { that.flag = false; let _delay = localDelay.delay - secTime; that.second = _delay; that.timer = setInterval(function() { if (_delay > 1) { _delay--; that.setStorage(_delay); that.second = _delay; that.flag = false; } else {
// 此处赋值时为了让浏览器打开的时候,直接就显示剩余的时间
that.flag = true; window.clearInterval(that.timer); } }, 1000); } }
然后在html挂载页面完成后的生命钩子(mounted)中调用judgeCode()方法就能实现该功能了