JavaScript数据持久化_LocalStorage封装

封装LocalStorage因原生API仅支持字符串、无过期机制、缺乏错误处理;通过StorageUtil类实现序列化、异常捕获、过期控制,提升安全性与易用性,并可扩展监听、加密等功能。

前端开发中,经常需要在浏览器端保存一些用户数据,比如用户偏好、登录状态或表单内容。LocalStorage 提供了简单易用的本地存储方案,但原生 API 操作不够友好,缺乏类型支持和异常处理。因此,封装一个更安全、易用的 LocalStorage 工具类非常有必要。

为什么需要封装 LocalStorage?

虽然 LocalStorage 的 API 很简单(setItem、getItem、removeItem),但它存在几个痛点:

  • 只支持字符串:存取对象需手动 JSON 序列化,容易出错。
  • 无过期机制:数据永久保存,无法自动清理。
  • 缺少错误处理:在隐私模式或存储空间满时操作会抛错。
  • 重复代码多:每次使用都要写 try-catch 和 JSON 转换。

基础封装:支持序列化与异常处理

封装一个 StorageUtil 类,解决类型转换和异常问题:

class StorageUtil {
  static set(key, value) {
    try {
      const serialized = JSON.stringify(value);
      localStorage.setItem(key, serialized);
    } catch (error) {
      console.warn(`保存 ${key} 失败`, error);
    }
  }

static get(key) { try { const item = localStorage.getItem(key); return item ? JSON.parse(item) : null; } catch (error) { console.warn(读取 ${key} 失败, error); return null; } }

static remove(key) { localStorage.removeItem(key); }

static clear() { localStorage.clear(); } }

这样调用就简洁多了:

StorageUtil.set('user', { name: 'Alice', age: 25 });
const user = StorageUtil.get('user'); // 直接返回对象

增强功能:添加过期时间

LocalStorage 本身不支持过期,但我们可以通过额外字段模拟:

class StorageUtil {
  // ... 其他方法

static setWithExpire(key, value, ttlMs) { const now = Date.now(); const item = { value, expire: now + ttlMs }; try { localStorage.setItem(key, JSON.stringify(item)); } catch (error) { console.warn(保存带过期的 ${key} 失败, error); } }

static getWithExpire(key) { try { const itemStr = localStorage.getItem(key); if (!itemStr) return null;

  const item = JSON.parse(itemStr);
  if (Date.now() > item.expire) {
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
} catch (error) {
  console.warn(`读取带过期的 ${key} 失败`, error);
  return null;
}

} }

使用示例:

// 10分钟后过期
StorageUtil.setWithExpire('token', 'abc123', 10 * 60 * 1000);
const token = StorageUtil.getWithExpire('token');

监听存储变化(可选)

LocalStorage 支持 storage 事件,可用于跨标签页通信:

window.addEventListener('storage', (event) => {
  if (event.key === 'user') {
    console.log('用户数据被其他页面修改:', event.newValue);
  }
});

注意:当前页面对 LocalStorage 的修改不会触发该事件。

基本上就这些。通过简单封装,我们让 LocalStorage 更安全、易用,还能扩展出过期控制等实用功能。实际项目中可根据需求进一步加入命名空间、加密存储等功能。不复杂但容易忽略细节。