【问题标题】:How to modify specify localstorage item in vuex?如何在 vuex 中修改指定的本地存储项?
【发布时间】:2020-01-27 16:46:00
【问题描述】:

我想在 vuex 中更改指定 localstorage 项。

例如,我有localstorage这样的项目:

{
  'id' = 1, 'another' = 2
}

我只想更改id,我该怎么做?

我只知道这样的基本用法:

localStorage.setItem("user", JSON.stringify(state.currentUser))

我尝试了类似的方法,但看起来它不起作用

localStorage.setItem("user.id", "2")

【问题讨论】:

    标签: javascript vue.js local-storage vuex


    【解决方案1】:

    您不能完全正确,因为 localStorage 将所有内容都存储为字符串。最好的方法是修改后再次用JSON.stringify-ing 替换整个对象。

    所以本质上:

    // Get the user from localStorage and parse into object
    let user = JSON.parse(localStorage.getItem("user"));
    // Update an attribute on the user object
    user.id = 2;
    // Update the user in localStorage and stringify to string
    localStorage.setItem("user", JSON.stringify(user));
    

    【讨论】:

    • 我认为您需要在user 项目当前不存在的情况下进行空检查,以避免id of null 行中的id of null 错误user.id = 2
    • 好主意@HarunYilmaz ?
    • @DelenaMalan 你可以在这里完善我的代码github.com/jazuly1/error/blob/master/1.js
    【解决方案2】:

    您可以使用getItem() 获取当前值并使用spread operator 分配值,如下所示:

    const newValue = {
       ...JSON.parse(localStorage.getItem("user")),
       id: 2
    }
    
    localStorage.setItem("user", JSON.stringify(newValue))
    

    【讨论】:

    • 是的,它的工作,但需要刷新才能生效。因为我使用的是路由器链接,所以我没有刷新页面..
    • 我认为您不需要刷新页面。我不知道Vue.js,但我认为您需要在分配值后调用相关的功能/服务才能生效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2023-02-25
    • 2021-01-24
    • 2021-10-24
    • 2014-06-20
    • 1970-01-01
    相关资源
    最近更新 更多