欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用js-cookie實(shí)現(xiàn)前端設(shè)置緩存數(shù)據(jù)定時(shí)失效

 更新時(shí)間:2019年06月18日 09:42:11   作者:bayi_lzp  
這篇文章主要介紹了利用js-cookie實(shí)現(xiàn)前端設(shè)置緩存數(shù)據(jù)定時(shí)失效,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、背景

業(yè)務(wù)需要在前端進(jìn)行數(shù)據(jù)的緩存,到期就刪除再進(jìn)行獲取新數(shù)據(jù)。

二、實(shí)現(xiàn)過程

前端設(shè)置數(shù)據(jù)定時(shí)失效的可以有下面2種方法:

1、當(dāng)數(shù)據(jù)較大時(shí),可以利用localstorage,存數(shù)據(jù)時(shí)候?qū)懭胍粋€(gè)時(shí)間,獲取的時(shí)候再與當(dāng)前時(shí)間進(jìn)行比較
2、如果數(shù)據(jù)不超過cookie的限制大小,可以利用cookie比較方便,直接設(shè)置有效期即可。
3、更多(請(qǐng)大神指點(diǎn))

利用localstorage實(shí)現(xiàn)

localstorage實(shí)現(xiàn)思路:

1、存儲(chǔ)數(shù)據(jù)時(shí)加上時(shí)間戳

在項(xiàng)目開發(fā)中,我們可以寫一個(gè)公用的方法來進(jìn)行存儲(chǔ)的時(shí)候加上時(shí)間戳

export function setLocalStorageAndTime (key, value) {
 window.localStorage.setItem(key, JSON.stringify({ data: value, time: new Date().getTime() }))
}

項(xiàng)目中應(yīng)用

存儲(chǔ)

 // 有數(shù)據(jù)再進(jìn)行存儲(chǔ)
   setLocalStorageAndTime('XXX', {name: 'XXX'})

讀取

// 判斷是否返回為null或者失效
getLocalStorageAndTime('XXX', 86400000)

2、獲取數(shù)據(jù)時(shí)與當(dāng)前時(shí)間進(jìn)行比較

export function getLocalStorageAndTime (key, exp = 86400000) {
 // 獲取數(shù)據(jù)
 let data = window.localStorage.getItem(key)
 if (!data) return null
 let dataObj = JSON.parse(data)
 // 與過期時(shí)間比較
 if (new Date().getTime() - dataObj.time > exp) {
  // 過期刪除返回null
  removeLocalStorage(key)
  console.log('信息已過期')
  return null
 } else {
  return dataObj.data
 }
}

利用cookie實(shí)現(xiàn)

我們用js-cookie這款插件來設(shè)置cookie,比較方便,可以自行查看文檔。

js-cookie 的示例中只有以天為單位的有效期:

Cookies.set('name', 'value', { expires: 7 }); // 7 天后失效

官方文檔只要設(shè)置天數(shù),沒有時(shí)分秒,這樣我們想設(shè)置更小單位的時(shí)候無法下手,其實(shí)也可以設(shè)置時(shí)間戳來處理時(shí)間的,下面這種方式可以設(shè)置任意單位的有效期:

let seconds = 10;
let expires = new Date(new Date() * 1 + seconds * 1000);
Cookies.set('username', 'tanggaowei', { expires: expires }); // 10 秒后失效

貼上利用js-cookie的封裝, 記得 npm i js-cookie

import Cookies from 'js-cookie'

/*
* 設(shè)置cookies
* */
export function getCookies (key) {
 return Cookies.get(key)
}
/*
* 設(shè)置Cookies
* */
export function setCookies (key, value, expiresTime) {
 let seconds = expiresTime
 let expires = new Date(new Date() * 1 + seconds * 1000)
 return Cookies.set(key, value, { expires: expires })
}
/*
* 移除Cookies
* */
export function removeCookies (key) {
 return Cookies.remove(key)
}

三、總結(jié)

上面兩個(gè)方法各有各的優(yōu)點(diǎn)和缺點(diǎn),如果小伙伴們有更好方法,麻煩留言互相學(xué)習(xí)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論