前端浏览器缓存(session,local)封装

732 阅读1分钟

为了方便管理缓存,及解决版本升级存储格式不统一存在历史缓存问题。如下:

方式一: 直接上代码

export const setSession = (name, val) => {
  return sessionStorage.setItem(name, JSON.stringify({ v: val }));
};

// 解决
export const getSession = (name) => {
  if (!sessionStorage.getItem(name)) {
    return "";
  } else {
  // 下面这段代码解决版本升级浏览器储存历史缓存问题
    let v = "";
    try {
      v = JSON.parse(sessionStorage.getItem(name)).v; //try---如果‘name’是个{},并且存在set赋值得v。那么return v 出去,否则catch抛出去
      if (v === undefined) { // if判断---如果对象v属性不存在或者‘name’是个数组或字符串,
        v = JSON.parse(sessionStorage.getItem(name));
      }
    } catch (e) {
      v = sessionStorage.getItem(name);
    }
    return v;
    
  }
};

export const setLocal = (name, val) => {
  return localStorage.setItem(name, JSON.stringify({ v: val }));
};

export const getLocal = (name) => {
  if (!JSON.parse(localStorage.getItem(name))) {
    return "";
  } else {
    let v = "";
    try {
      v = JSON.parse(localStorage.getItem(name)).v;
      if (v === undefined) {
        v = JSON.parse(localStorage.getItem(name));
      }
    } catch (e) {
      v = localStorage.getItem(name);
    }
    return v;
  }
};

export const sessionClear = () => {
  return sessionStorage.clear();
};

export const localClear = () => {
  return localStorage.clear();
};

export const removeSession = (name) => {
  return sessionStorage.removeItem(name);
};

方式二: 在项目里写的最后登录时间戳,并存到缓存中,下次登录对比,超时就强制清掉所有缓存。