【问题标题】:How to clear completely the data in vuex?如何彻底清除vuex中的数据?
【发布时间】:2021-07-22 23:53:45
【问题描述】:

我在一个应用程序中使用 Vuetify/Vue/Vuex,很多公司都有很多项目。

用户可以从一家公司切换到另一家公司:

export const setCompany = ({ commit, dispatch }, id) => {
    dispatch('resetData').then(function (){
        return axios.post(`/api/setCompany/${id}`).then((response) => {
            location.href = 'https://example.com/#/dashboard'
            location.reload()
        })
    })
}

export const resetData = ({ dispatch,commit }) => {
    commit('projects/SET_PROJECTS_DATA', [], {root: true})
    commit('projects/SET_PROJECT_DATA', [], {root: true})
    commit('issues/SET_ISSUES_DATA', [], {root: true})
    commit('issues/SET_ISSUE_DATA', [], {root: true})
    commit('todos/SET_TODOS_DATA', [], {root: true})
    commit('todos/SET_TODO_DATA', [], {root: true})
    commit('potentials/SET_POTENTIALS_DATA', [], {root: true})
    commit('potentials/SET_POTENTIAL_DATA', [], {root: true})
}

当我在“老”公司工作时,我有一份这家公司的项目清单。

当我切换到新公司时,我仍然有相同的项目(来自旧公司)。重新加载时不会清除项目列表。

我尝试在重新加载后检查 vuex 状态“项目/项目”和“项目/项目”。这些变量是空的。但是在项目列表中,还是出现了之前公司的项目。

我必须在哪里清理数据以获得一个空的项目列表?

【问题讨论】:

  • resetData 对我来说看起来不错。换公司时为什么不打电话呢?
  • @Deniz 我调用它,当我检查后(评论 location.href 和评论 location reload())“项目/项目”的状态为空。页面重新加载后也是如此。但是不知道为什么,项目列表还在……
  • 切换公司时,您是否使用相同的存储projects 存储数据?
  • 是的,我称之为相同的数据。但我想,用 resetData 我会清除它。
  • 嗨,我的回答有帮助吗?

标签: vue.js vuex


【解决方案1】:

我确实使用这个解决方案:https://github.com/vuejs/vuex/issues/1118#issuecomment-356286218

实际上,您可以在 github 线程中寻找很多可能的方法来执行此操作。

function initialState () {
  return { /* .. initial state ... */ }
}

export default {
  state: initialState,

  mutations: {
    reset (state) {
      // acquire initial state
      const s = initialState()
      Object.keys(s).forEach(key => {
        state[key] = s[key]
      })
    }
  }
}

你也有这个解决方案:https://forum.vuejs.org/t/how-to-completely-reset-the-vuex-store/13611/5

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2020-07-05
    • 1970-01-01
    • 2016-09-18
    • 2014-10-06
    • 2012-10-14
    • 2013-10-05
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多