Vue利用localStorage本地緩存使頁面刷新驗證碼不清零功能的實現(xiàn)
今天我們使用本地緩存localStorage來實現(xiàn)頁面刷新了,驗證碼倒計時還是和刷新時一樣,而不是清零,其次我們可以使用localStorage去實現(xiàn)用戶信息緩存,記住密碼等等關(guān)于緩存的功能,在這里就簡單演示一下驗證碼功能。
一、功能實現(xiàn)
話不多說,直接上代碼
<template> <button @click="getCode()" :disabled="!show"> <span v-show="show">發(fā)送驗證碼</span> <span v-show="!show" class="count">{{count}} s</span> </button> </template>
<script> let TIME_COUNT = 60; // 設(shè)置一個全局的倒計時的時間 export default { data() { return { show: true, count: '', timer: null, } }, components: { marquee }, created(){ // 進入頁面時獲取倒計時中止的位置,并繼續(xù)計時 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 三大緩存的主要區(qū)別
1)存儲大小
- cookie數(shù)據(jù)大小不能超過4k。
- sessionStorage和localStorage 雖然也有存儲大小的限制,但比cookie大得多,可以達到5M或更大。
2)有效時間
- localStorage:存儲持久數(shù)據(jù),瀏覽器關(guān)閉后數(shù)據(jù)不丟失除非主動刪除數(shù)據(jù);
- sessionStorage:數(shù)據(jù)在當前瀏覽器窗口關(guān)閉后自動刪除。
- cookie:設(shè)置的cookie過期時間之前一直有效,即使窗口或瀏覽器關(guān)閉,
3)數(shù)據(jù)與服務(wù)器之間的交互方式
- cookie的數(shù)據(jù)會自動的傳遞到服務(wù)器,服務(wù)器端也可以寫cookie到客戶端。
- sessionStorage僅在本地保存,只能在同一標簽下共享。
- localStorage僅在本地保存,同一瀏覽器,標簽頁全部共享。
4)適合場景使用
- localStorage:適合用于用戶離開不清除的數(shù)據(jù),如記住密碼。
- sessionStorage:適合用于做一些用戶離開時及清除的數(shù)據(jù),如用戶信息。
- cookie:適合用于和服務(wù)器交互的數(shù)據(jù),如用戶發(fā)起請求的唯一憑證。
當然只是說誰更適合,存在即合理,別和我杠。
2.localStorage寫法
localStorage.getItem("code")//或localStorage.code或localStorage["code"],獲取code localStorage.setItem("code","A")//或localStorage.code="A"或localStorage["code"]="A",存儲code localStorage.removeItem("code")//存儲的持久數(shù)據(jù)不清除是不會丟失的,清除code localStorage.clear(); //清除本地全部localStorage緩存
總結(jié)
到此這篇關(guān)于Vue利用localStorage本地緩存使頁面刷新驗證碼不清零的文章就介紹到這了,更多相關(guān)Vue頁面刷新驗證碼不清零內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于vue-cli、elementUI的Vue超簡單入門小例子(推薦)
這篇文章主要介紹了基于vue-cli、elementUI的Vue超簡單入門小例子,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04VUE Error: getaddrinfo ENOTFOUND localhost
這篇文章主要介紹了VUE Error: getaddrinfo ENOTFOUND localhost,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05