typecho通过Cookie实现浏览足迹功能
5个月前 > 首先声明,下面的代码基本都是用AI写作,博主只是辅助提供意见修改。...
项目中用到的一个localStorage工具,可以用于token存储、数据缓存,支持过期,使用起来简答快捷
JavaScript版
const DEFAULT_EXPIRE = 7200; // 默认存储时间(秒)
const cache = {
/**
* 设置缓存
* @param {string} key 存储的键
* @param {any} value 存储的值
* @param {number} [expire=DEFAULT_EXPIRE] 过期时间(秒),默认 7200s
*/
set: (key, value, expire = DEFAULT_EXPIRE) => {
const expireTimestamp = Date.now() expire * 1000;
const cacheData = { data: value, expireTimestamp };
localStorage.setItem(key, JSON.stringify(cacheData));
},
/**
* 获取缓存
* @param {string} key 存储的键
* @param {any} [defaultValue=null] 如果缓存不存在,返回的默认值
* @returns {any|null} 获取到的数据,或者默认值
*/
get: (key, defaultValue = null) => {
const item = localStorage.getItem(key);
if (!item) return defaultValue;
try {
const cacheData = JSON.parse(item);
if (Date.now() > cacheData.expireTimestamp) {
cache.remove(key); // 过期后删除
return defaultValue;
}
return cacheData.data;
} catch (error) {
console.error("解析缓存数据失败:", error);
cache.remove(key);
return defaultValue;
}
},
/**
* 删除缓存
* @param {string} key 存储的键
*/
remove: (key) => {
localStorage.removeItem(key);
},
/**
* 清空所有缓存
*/
clear: () => {
localStorage.clear();
}
};
export default cache;
typeScript版
const DEFAULT_EXPIRE = 7200; // 默认存储时间(秒)
interface CacheData<T> {
data: T;
expireTimestamp: number;
}
const cache = {
/**
* 设置缓存
* @param key 存储的键
* @param value 存储的值
* @param expire 过期时间(秒),默认 7200s
*/
set: <T>(key: string, value: T, expire: number = DEFAULT_EXPIRE) => {
const expireTimestamp = Date.now() expire * 1000;
const cacheData: CacheData<T> = { data: value, expireTimestamp };
localStorage.setItem(key, JSON.stringify(cacheData));
},
/**
* 获取缓存
* @param key 存储的键
* @param defaultValue 如果缓存不存在,返回的默认值
* @returns T | null
*/
get: <T>(key: string, defaultValue: T | null = null): T | null => {
const item = localStorage.getItem(key);
if (!item) return defaultValue;
try {
const cacheData: CacheData<T> = JSON.parse(item);
if (Date.now() > cacheData.expireTimestamp) {
cache.remove(key); // 过期后删除
return defaultValue;
}
return cacheData.data;
} catch (error) {
console.error("解析缓存数据失败:", error);
cache.remove(key);
return defaultValue;
}
},
/**
* 删除缓存
* @param key 存储的键
*/
remove: (key: string) => {
localStorage.removeItem(key);
},
/**
* 清空所有缓存
*/
clear: () => {
localStorage.clear();
}
};
export default cache;#免责声明#

5个月前 > 首先声明,下面的代码基本都是用AI写作,博主只是辅助提供意见修改。...

6个月前 > 例如:有时候需要把动态页面(前提是动态页面功能是通过评论改的)的...

5个月前 > **例如:**有时候需要把动态页面(前提是动态页面功能是通过评论改的)...

5个月前 ##### 进入插件管理页面 登录项目后台,导航至插件管理界面(对应代码中...

3个月前 # Equipment 类详细使用方法 ## 类概述 `Equipment` 类是玩家装备系统的核心组...

6个月前 前几天就准备重新设计一下轻博客的权限功能,最初的权限功能已经不能满...