亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue短信驗(yàn)證性能優(yōu)化如何寫入localstorage中

 更新時(shí)間:2018年04月25日 08:37:29   作者:Cynthia-milk  
這篇文章主要介紹了vue短信驗(yàn)證性能優(yōu)化寫入localstorage中的方法,解決這個(gè)問題需要把時(shí)間都寫到localstorage里面去,具體解決方法大家參考下本文

平時(shí)我們?cè)陧?xiàng)目中進(jìn)行注冊(cè)等的時(shí)候,會(huì)經(jīng)常用到短信驗(yàn)證的功能,但是現(xiàn)在現(xiàn)在很多短信驗(yàn)證都是存在下面幾個(gè)問題,例如短信驗(yàn)證時(shí)間為60s的時(shí)候,

1. 當(dāng)點(diǎn)擊完按鈕時(shí),倒計(jì)時(shí)還沒到60s過完時(shí),刷新瀏覽器,驗(yàn)證碼按鈕又可以重新點(diǎn)擊

2.當(dāng)點(diǎn)擊按鈕倒計(jì)時(shí)開始,例如在50s的時(shí)候我關(guān)閉了瀏覽器,過了5s后,我在打開,此時(shí)時(shí)間倒計(jì)時(shí)的時(shí)間應(yīng)該是45s左右,但是當(dāng)重新打開瀏覽器的時(shí)候,按鈕又可以重新點(diǎn)擊了

為了解決上面的兩個(gè)問題,就需要把時(shí)間都寫到localstorage里面去,當(dāng)打開頁(yè)面的時(shí)候,就去localstorage里面去取,我這里就貼上我的解決方法,因?yàn)榍皫滋煊袀€(gè)vue的項(xiàng)目用到該方法,所以我這里就寫個(gè)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>

重點(diǎn)來啦

在data里面定義幾個(gè)需要用到的變量:

 second: 60,
 flag: true,
 timer: null // 該變量是用來記錄定時(shí)器的,防止點(diǎn)擊的時(shí)候觸發(fā)多個(gè)setInterval

獲取短信驗(yàn)證的方法:

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;
  }

防止頁(yè)面刷新是驗(yàn)證碼失效:

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 {
             
              // 此處賦值時(shí)為了讓瀏覽器打開的時(shí)候,直接就顯示剩余的時(shí)間
      that.flag = true;
      window.clearInterval(that.timer);
     }
    }, 1000);
   }
  }

然后在html掛載頁(yè)面完成后的生命鉤子(mounted)中調(diào)用judgeCode()方法就能實(shí)現(xiàn)該功能了

總結(jié)

以上所述是小編給大家介紹的vue短信驗(yàn)證性能優(yōu)化如何寫入localstorage中,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論