一:起因
产品想要做表单缓存,且在一定时间没操作后清掉缓存。
二:方法
// 设置带过期时间的localstorage
export const setLocalStorageByExpires = function (key, value, expirationMinutes = 7 * 24 * 60) {
// expirationMinutes 是过期时间,以分钟为单位,默认7天
const expiration = expirationMinutes * 60 * 1000; // 毫秒数
const expires = new Date().getTime() + expiration;
const data = {
value: value,
expires: expires,
};
localStorage.setItem(key, JSON.stringify(data));
};
// 获取localstorage并判断过期
export const getLocalStorageByExpires = function (key) {
const data = JSON.parse(localStorage.getItem(key));
if (data && new Date().getTime() < data.expires) {
return data.value;
} else {
localStorage.removeItem(key);
return null;
}
};