當前位置:名人名言大全網 - 短信平臺 - 怎樣實現短信驗證優化

怎樣實現短信驗證優化

這次給大家帶來怎樣實現短信驗證優化,實現短信驗證優化的註意事項有哪些,下面就是實戰案例,壹起來看壹下。

平時我們在項目中進行註冊等的時候,會經常用到短信驗證的功能,但是現在現在很多短信驗證都是存在下面幾個問題,例如短信驗證時間為60s的時候,

1. 當點擊完按鈕時,倒計時還沒到60s過完時,刷新瀏覽器,驗證碼按鈕又可以重新點擊

2.當點擊按鈕倒計時開始,例如在50s的時候我關閉了瀏覽器,過了5s後,我在打開,此時時間倒計時的時間應該是45s左右,但是當重新打開瀏覽器的時候,按鈕又可以重新點擊了

為了解決上面的兩個問題,就需要把時間都寫到localstorage裏面去,當打開頁面的時候,就去localstorage裏面去取,我這裏就貼上我的解決方法,因為前幾天有個vue的項目用到該方法,所以我這裏就寫個vue的方法出來吧

組件裏面的html代碼:

<p 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>

</p>重點來啦

在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);

}

}相信看了本文案例妳已經掌握了方法,更多精彩請關註Gxl網其它相關文章!

推薦閱讀:

如何使用vuex操作state對象

怎樣使用node做出個人號機器人