【问题标题】:Vuex state not updating from local storageVuex 状态未从本地存储更新
【发布时间】:2019-03-26 12:18:10
【问题描述】:

当直接从隐身窗口中的地址栏访问路由时,我在从本地存储更新 Vuex 状态时遇到了一些问题。

当直接访问/shop/:key? 路由时(例如单击电子邮件中的链接),将执行挂载操作getDetail 并更新本地存储但未重新评估状态 - 它仍然显示未定义,就好像密钥没有不存在。

有没有办法让状态被重新评估,还是必须在setDetail 突变中更新?

const state = {
    key: localStorage.getItem('key'),
    details: null
}

const actions = {
    async getDetail({ commit }, key) {
        const details = await Service.detail(key)
        commit('setDetail', details)
    }
}

const mutations = {
    setDetail(state, details) {
        state.details = details
    }
}

const Service = {
    detail: async function(key) {
        const url = `/store/${key}/`
        const response = await ApiService.get(url)
        localStorage.setItem('key', key)
        return response.data
    }
}

【问题讨论】:

  • 这可以help:,你需要在组件创建时调用mutation。如果您需要,请告诉我,然后我可以为您创建一个演示

标签: vue.js vuex


【解决方案1】:

如果发生突变(或动作),将重新评估状态。您可以直接更改状态,但建议不要这样做,因为它会破坏反应性。

LocalStorage 不是响应式的,因此您需要使用mutationaction 更新状态。

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 2017-05-20
    • 2020-12-18
    • 2020-06-10
    • 2020-09-08
    • 2023-03-16
    • 2020-06-21
    • 2021-06-19
    • 2019-03-21
    相关资源
    最近更新 更多