localStorage和sessionStorage儲存封裝

Yseraaa發表於2024-11-16
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'    
}

  

相關文章