如何清除 vuex 商店中的状态? [英] How to clear state in vuex store?

查看:44
本文介绍了如何清除 vuex 商店中的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 vuex 商店的状态很大.

My state in vuex store is huge.

有没有办法一次性重置所有状态的数据,而不是手动将所有内容都设置为空?

Is there a way to reset all the data in state in one go, instead of manually setting everything to null?

推荐答案

我刚刚找到了适合我的出色解决方案.

I have just found the great solution that works for me.

const getDefaultState = () => {
  return {
    items: [],
    status: 'empty'
  }
}

// initial state
const state = getDefaultState()

const actions = {
  resetCartState ({ commit }) {
    commit('resetState')
  },
  addItem ({ state, commit }, item) { /* ... */ }
}

const mutations = {
  resetState (state) {
    // Merge rather than replace so we don't lose observers
    // https://github.com/vuejs/vuex/issues/1118
    Object.assign(state, getDefaultState())
  }
}

export default {
  state,
  getters: {},
  actions,
  mutations
}

感谢 Taha Shashtari 的出色解决方案.

Thanks to Taha Shashtari for the great solution.

迈克尔

这篇关于如何清除 vuex 商店中的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆