之前如果是一个key对应一个value值的话,在get的时候只能判断当下的一条数据是否过期,并不能实现自动清理过期的脏数据,所以我们把localstorage的数据格式定义成如下
key:"barringType" //这是一个写死的字符串
value:{
"2155644866": //这是一个唯一的id值 weID
[
{
"id": "1",
"content": "111",
"time": 1660526786413,
"duration": 30000
},
{
"id": "2",
"content": "222",
"time": 1660526783688,
"duration": 30000
},
]}
封装localstorage方法
export const storage = {
/*
* set 存储方法
* @ param {String} key 键
* @ param {String} value 值,
*/
set(key:string, val:string) {
if (typeof val !== 'string') {
val = JSON.stringify(val);
}
window.localStorage.setItem(key, val);
},
/*
* get 获取方法
* @ param {String} key 键
* @ param {String} weID id
*/
get(key:string, weID:string) {
const EXPIRED = 1000 * 60 * 60 * 24 * 2; // 清理时间暂定两天
const now = Date.now();
let val:any = window.localStorage.getItem(key);
if (!val) return null;
try {
val = JSON.parse(val);
Object.keys(val).forEach((key) => {
if (now - val[key][0].time > EXPIRED) {
delete val[key];
}
});
} catch (e) {
console.log(`${val} Unexpected token H in JSON at position 0`);
}
const result = val[meetingID];
return result;
},
/**
* clear 清空
*/
clear() {
window.localStorage.clear();
},
/*
* remove 移除
* */
remove(key:string) {
let val:any = window.localStorage.getItem(key);
val = JSON.parse(val);
delete val.key;
},
};
设置值的过程,拼接对应的数据结构
const bRStorage:any = {};
bRStorage[weID] = barrageRecord.value;
storage.set(
'barringType',
JSON.stringify(bRStorage),
);
取出值的过程
barrageRecord.value = storage.get('barringType', weID)