前言:
我們知道localStorage如果設置了,那麼默認是永久有效的,除非手動進行刪除。
手動刪除
:可以在谷歌瀏覽器控制檯的Application => Local Storage 中找到自己要刪除的文件/域名中的某一項數據雙擊進行清空刪除即可。
自定義過期時間:
默認localStorage的api中時不支持設置過期時間的,所以我們只能對localStorage進行二次封裝。
自定義過期時間實現的思路:
1、在設置localStorage數據的時候傳入過期時間參數,然後自定義個鍵名來保存過期時間,這個鍵名要和設置數據的鍵名有關聯。
2、獲取localStorage數據的時候先判斷過期時間鍵名保存的時間和當前時間的毫秒數,如果當前時間的毫秒數還大的話就表示數據過期了,那麼就刪除過期數據
注意點:
1、存儲的值可能是數組/對象,不能直接存儲,需要轉換,使用 JSON.stringify()。
2、設置到localStorage中的數據格式都爲字符串類型,就算你設置時是數字類型,獲取的時候也是字符串類型了。
具體代碼實現:
class storage {
constructor() {
this.source = window.localStorage;
this.initClear();
}
/**
* 初始化清除已經過期的數據
*/
initClear(){
// const reg = new RegExp("__expires__");
const reg = /__expires__/;
let data = this.source;
let list = Object.keys(data);
if(list.length > 0){
list.forEach((key) => {
// 如果爲非包含__expires__鍵名的key進行判斷清除過期的
if( !reg.test(key)){
let now = Date.now();
let expires = data[`${key}__expires__`];
if (now >= expires ) {
this.remove(key);
}
}
})
};
}
/**
* set 存儲方法
* @ param {String} key 鍵名
* @ param {String} value 鍵值
* @ param {String} expired 過期時間,以分鐘爲單位,非必須。(不傳則爲永久有效)
*/
set(key, value, expired) {
let source = this.source;
source[key] = JSON.stringify(value);
if (expired !== undefined){
// // 過期時間單位爲天
// source[`${key}__expires__`] = Date.now() + 1000 * 60 * 60 * 24 * expired
// // 過期時間單位爲小時
// source[`${key}__expires__`] = Date.now() + 1000 * 60 * 60 * expired
// 過期時間單位爲分鐘
source[`${key}__expires__`] = Date.now() + 1000 * 60 * expired;
};
}
/**
* get 獲取方法
* @ param {String} key 鍵名
* @ return 如果沒過期則返回數據,否則返回null
*/
get(key) {
const source = this.source;
const expires = source[`${key}__expires__`];
// 獲取前把已經過期的數據刪除掉
if (expires) {
const now = Date.now();
if ( now >= expires ) {
this.remove(key);
return null;
}
}
// 獲取數據
const value = source[key] ? JSON.parse(source[key]) : null;
return value;
}
/**
* remove 刪除方法
* @ param {String} key 鍵名 非必須 (不傳則刪除所有)
*/
remove(key) {
if (key) {
// localStorage自帶的removeItem()方法
this.source.removeItem(key);
this.source.removeItem(`${key}__expires__`);
// delete data[key];
// delete data[`${key}__expires__`];
} else {
// 清除所有,localStorage自帶的clear()方法
this.source.clear();
}
}
}
let myLocalStorage = new storage()
myLocalStorage.set('name', 'winne')
myLocalStorage.set('age', '100', 30)
myLocalStorage.set('num', '88', 0)
myLocalStorage.set('oneMinute', '22', 1)
myLocalStorage.set('obj', {name: 'xf'}, 10)
console.log(myLocalStorage.get('name')) // 'winne'
console.log(myLocalStorage.get('age')) // '100'
console.log(myLocalStorage.get('num')) // null
console.log(myLocalStorage.get('oneMinute')) // '22'
console.log(myLocalStorage.get('obj')) // {name: "xf"}
// myLocalStorage.remove('age')
// myLocalStorage.remove()
運行圖:
資料參考:
https://blog.csdn.net/weixin_43254766/article/details/83618630