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'],獲取codelocalStorage.setItem('code','A')//或localStorage.code='A'或localStorage['code']='A',存儲codelocalStorage.removeItem('code')//存儲的持久數據不清除是不會丟失的,清除codelocalStorage.clear(); //清除本地全部localStorage緩存
總結
到此這篇關于Vue利用localStorage本地緩存使頁面刷新驗證碼不清零的文章就介紹到這了,更多相關Vue頁面刷新驗證碼不清零內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: