You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何更新Local Storage中的对象——以更新unread_notifications属性为例

如何更新LocalStorage中用户对象的unread_notifications属性

嘿,我来帮你一步步搞定这个操作~因为LocalStorage只能存储字符串,所以更新对象属性需要走「取出来→转成对象→修改→转字符串→存回去」的流程,具体步骤如下:

详细操作步骤

  • 第一步:获取存储的用户信息字符串
    先用localStorage.getItem(USER_INFO)拿到存储的字符串,记得要处理可能返回null的情况(比如用户还没登录过):

    const USER_INFO = 'userInfo'; // 假设你的key是这个,根据实际情况调整
    const userInfoStr = localStorage.getItem(USER_INFO);
    
  • 第二步:解析为JavaScript对象
    把字符串转成可操作的JS对象,如果获取到的不是null才解析:

    if (!userInfoStr) {
      console.log('用户信息不存在,请先登录');
      return; // 或者做其他适配处理
    }
    const userData = JSON.parse(userInfoStr);
    
  • 第三步:修改unread_notifications属性
    这一步根据你的实际需求来操作,举几个常见场景:

    1. 清空所有未读通知:
      userData.unread_notifications = [];
      
    2. 添加一条新的未读通知:
      const newNotification = { id: 2, content: '您有一条新的订单提醒', createdAt: new Date().toISOString() };
      userData.unread_notifications.push(newNotification);
      
    3. 替换整个未读通知数组(比如从后端获取了最新的列表):
      const updatedNotifications = [/* 后端返回的最新未读通知数组 */];
      userData.unread_notifications = updatedNotifications;
      
  • 第四步:将修改后的对象转回字符串
    LocalStorage不能直接存对象,必须转成JSON字符串:

    const updatedUserInfoStr = JSON.stringify(userData);
    
  • 第五步:重新存储回LocalStorage
    用setItem覆盖原来的存储项:

    localStorage.setItem(USER_INFO, updatedUserInfoStr);
    

完整示例代码

把上面的步骤整合起来,比如清空未读通知的完整代码:

const USER_INFO = 'userInfo';
const userInfoStr = localStorage.getItem(USER_INFO);

if (userInfoStr) {
  const userData = JSON.parse(userInfoStr);
  // 修改unread_notifications
  userData.unread_notifications = [];
  // 重新存储
  localStorage.setItem(USER_INFO, JSON.stringify(userData));
  console.log('未读通知已清空');
} else {
  console.log('未找到用户信息,请检查存储key或登录状态');
}

注意事项

  • 一定要确保USER_INFO这个key和你存储时用的完全一致,大小写也要匹配哦。
  • 如果unread_notifications原本不存在,直接赋值也没问题,JS会自动给对象添加这个属性。
  • 处理null的情况很重要,避免因为用户信息不存在导致JSON.parse报错。

内容的提问来源于stack exchange,提问作者Bilal Arshad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:17:48