const createStorageProxy = (target = {}, type: 'local' | 'session') => {
  const storage = type === 'local' ? localStorage : sessionStorage;
  return new Proxy(target, {
    get(obj: Record<string, any>, prop: string) {
      const value = storage.getItem(prop);
      return value !== null ? JSON.parse(value) : obj[prop];
    },
    set(obj: Record<string, any>, prop: string, value: any) {
      if (value === undefined) {
        storage.removeItem(prop);
      } else {
        storage.setItem(prop, JSON.stringify(value));
      }
      obj[prop] = value;
      return true;
    },
  });
};

export const LocalStorage = createStorageProxy({}, 'local');
export const SessionStorage = createStorageProxy({}, 'session');

使用方法:

存:

LocalStorage.userInfo = {
  name: 'Ysera'    
}

  

 posted on 2024-11-16 14:45  Yseraaa  阅读(9)  评论(0编辑  收藏  举报