1. 程式人生 > 程式設計 >Vue利用localStorage本地快取使頁面重新整理驗證碼不清零功能的實現

Vue利用localStorage本地快取使頁面重新整理驗證碼不清零功能的實現

今天我們使用本地快取localStorage來實現頁面重新整理了,驗證碼倒計時還是和重新整理時一樣,而不是清零,其次我們可以使用localStorage去實現使用者資訊快取,記住密碼等等關於快取的功能,在這裡就簡單演示一下驗證碼功能。

一、功能實現

話不多說,直接上程式碼

<template>
	<button @click="getCode()" :disabled="!show">
  <span v-show="show">傳送驗證碼</span>
  <span v-show="!show" class="count">{{count}} s</span>
 </button>
</template>
<script>
 let TIME_COUNT = 60; // 設定一個全域性的倒計時的時間
 export default {
 data() {
  return {
   show: true,count: '',timer: null,}
 },components: {
  marquee
 },created(){
   // 進入頁面時獲取倒計時中止的位置,並繼續計時
   if (localStorage.regtime > 0 && localStorage.regtime <= TIME_COUNT){
    TIME_COUNT = localStorage.regtime;
    this.count = TIME_COUNT;
    this.show = false;
    this.timer = setInterval(() => {
     if (this.count > 0 && this.count <= TIME_COUNT) {
      this.count--
      localStorage.regtime = this.count;
     } else {
      this.show = true;
      clearInterval(this.timer);
      this.timer = null
     }
    },1000)
   }
 },methods: {
  getCode () {
   // 驗證碼倒計時
   if (!this.timer) {
    this.count = TIME_COUNT
    localStorage.regtime = this.count;
    this.show = false
    this.timer = setInterval(() => {
    if (this.count > 0 && this.count <= TIME_COUNT) {
     this.count--
     localStorage.regtime = this.count;
    } else {
     this.show = true
     clearInterval(this.timer)
     this.timer = null
    }
   },1000)
  }
 }
 }
</script>

二、知識拓展

1.對比cookies,sessionStorage 和 localStorage 三大快取的主要區別

1)儲存大小

  • cookie資料大小不能超過4k。
  • sessionStorage和localStorage 雖然也有儲存大小的限制,但比cookie大得多,可以達到5M或更大。

2)有效時間

  • localStorage:儲存持久資料,瀏覽器關閉後資料不丟失除非主動刪除資料;
  • sessionStorage:資料在當前瀏覽器視窗關閉後自動刪除。
  • cookie:設定的cookie過期時間之前一直有效,即使視窗或瀏覽器關閉,

3)資料與伺服器之間的互動方式

  • cookie的資料會自動的傳遞到伺服器,伺服器端也可以寫cookie到客戶端。
  • sessionStorage僅在本地儲存,只能在同一標籤下共享。
  • localStorage僅在本地儲存,同一瀏覽器,標籤頁全部共享。

4)適合場景使用

  • localStorage:適合用於使用者離開不清除的資料,如記住密碼。
  • sessionStorage:適合用於做一些使用者離開時及清除的資料,如使用者資訊。
  • cookie:適合用於和伺服器互動的資料,如使用者發起請求的唯一憑證。

當然只是說誰更適合,存在即合理,別和我槓。

2.localStorage寫法

localStorage.getItem("code")//或localStorage.code或localStorage["code"],獲取code
localStorage.setItem("code","A")//或localStorage.code="A"或localStorage["code"]="A",儲存code
localStorage.removeItem("code")//儲存的持久資料不清除是不會丟失的,清除code
localStorage.clear(); //清除本地全部localStorage快取

總結

到此這篇關於Vue利用localStorage本地快取使頁面重新整理驗證碼不清零的文章就介紹到這了,更多相關Vue頁面重新整理驗證碼不清零內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!