vue项目--- 新建文件sessionTime.js 文件
/** @desc storage相关 */
// type TStorageItem = {
// value: any
// expire: string|number
// time: Date
// };
// type = 'localStorage' | 'sessionStorage'
/**
* @desc 设置storage
* @param key 键
* @param value 值
* @param exprie 过期时间,如果是数值,多长时间后清除,单位毫秒,如果是string,则表示哪个时间清除
*/
const setStorage = (storageName, key, value, expire) => {
try {
const data = {
value, // 值
expire, // 过期时间
time: new Date(), // 存的时间
};
window[storageName].setItem(key, encodeURIComponent(JSON.stringify(data)));
} catch (err) {
// 失败不管
}
};
/**
* @desc 获取storage
* @param key 键
* @param return 1为错误 0为过期 value为未过期并返回存入的数据
*/
const getStorage = (storageName, key) => {
try {
const data = window[storageName].getItem(key);
// 转换
const obj = JSON.parse(decodeURIComponent(data));
const { value, expire, time } = obj;
const now = new Date().getTime();
// 判断有没有过期
if (typeof expire =='number') {
const delta = now - (new Date(time).getTime());
if (delta > expire) {
window[storageName].removeItem(key);
return 0;
}
}
if (typeof expire == 'string') {
const endTime = new Date(expire).getTime();
const delta = now - endTime;
if (delta >= 0) {
window[storageName].removeItem(key);
return 0;
}
}
return value;
} catch (err) {
// console.log(err)
return 1;
}
};
/** @desc 设置localStorage */
export const setLocalStorage = (key, value, expire) => {
setStorage('localStorage', key, value, expire);
};
/** @desc 获取localStorage */
export const getLocalStorage = (key) => getStorage('localStorage', key);
/** @desc 删除localStorage */
export const delLocalStorage = (key) => {
localStorage.removeItem(key);
};
/** @desc 设置sessionStorage */
export const setSessionStorage = (key , value, expire) => {
setStorage('sessionStorage', key, value, expire);
};
/** @desc 获取sessionStorage */
export const getSessionStorage = (key) => getStorage('sessionStorage', key);
/** @desc 删除localStorage */
export const delSessionStorage = (key) => {
sessionStorage.removeItem(key);
};
/** @desc 正常获取localStorage */
export const localStorageNormal = (key, value) => {
if (value !== undefined) {
return window.localStorage.setItem(key, value);
}
return window.localStorage.getItem(key);
};
在页面使用:
setLocalStorage('存入数据的名称',要存入的数据, 时间毫秒)
如:1000*60*60*24
一天过期,当天凌晨过期可查看另一篇
getLocalStorage('存入数据的名称')
其他逻辑自行添加