How to clear state in vuex store?

2019-03-12 16:25发布

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?

6条回答
beautiful°
2楼-- · 2019-03-12 16:57

If you do a state = {}, you will remove the reactivity of the properties and your getters mutations will suddenly stop working.

you can have a sub-property like:

state: {
  subProperty: {
    a: '',
    lot: '',
    of: '',
    properties: '',
    .
    .
    .
  }
}

Doing a state.subProperty = {} should help, without losing the reactivity.

You should not have a state too big, break them down to different modules and import to your vuex store like so:

import Vue from 'vue'
import Vuex from 'vuex'
import authorization from './modules/authorization'
import profile from './modules/profile'

Vue.use(Vuex)

export const store = new Vuex.Store({
  modules: {
    authorization,
    profile
  }
})

now in your individual files:

// modules/authorization.js
import * as NameSpace from '../NameSpace'
import { someService } from '../../Services/something'

const state = {
  [NameSpace.AUTH_STATE]: {
    auth: {},
    error: null
  }
}

const getters = {
  [NameSpace.AUTH_GETTER]: state => {
    return state[NameSpace.AUTH_STATE]
  }
}

const mutations = {
  [NameSpace.AUTH_MUTATION]: (state, payload) => {
    state[NameSpace.AUTH_STATE] = payload
  },
}

const actions = {
  [NameSpace.ASYNC_AUTH_ACTION]: ({ commit }, payload) => {
    someService.login(payload.username, payload.password)
      .then((user) => {
        commit(NameSpace.AUTH_MUTATION, {auth: user, error: null})
      })
      .catch((error) => {
        commit(NameSpace.AUTH_MUTATION, {auth: [], error: error})
      })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

If you should want to clear the state you can just have a mutation implement:

state[NameSpace.AUTH_STATE] = {
  auth: {},
  error: null
}
查看更多
走好不送
3楼-- · 2019-03-12 17:05

Update after using the below solution a bit more

So it turns out that if you use replaceState with an empty object ({}) you end up bricking reactivity since your state props go away. So in essence you have to actually reset every property in state and then use store.replaceState(resetStateObject). For store without modules you'd essentially do something like:

let state = this.$store.state;
let newState = {};

Object.keys(state).forEach(key => {
  newState[key] = null; // or = initialState[key]
});

this.$store.replaceState(newState);

Update (from comments): What if one needs to only reset/define a single module and keep the rest as they were?

If you don't want to reset all your modules, you can just reset the modules you need and leave the other reset in their current state.

For example, say you have mutliple modules and you only want to reset module a to it's initial state, using the method above^, which we'll call resetStateA. Then you would clone the original state (that includes all the modules before resetting).

var currentState = deepClone(this.state)

where deepClone is your deep cloning method of choice (lodash has a good one). This clone has the current state of A before the reset. So let's overwrite that

var newState = Object.assign(currentState, {
  a: resetStateA
});

and use that new state with replaceState, which includes the current state of all you modules, except the module a with its initial state:

this.$store.replaceState(newState);

Original solution

I found this handy method in Vuex.store. You can clear all state quickly and painlessly by using replaceState, like this:

store.replaceState({})

It works with a single store or with modules, and it preserves the reactivity of all your state properties. See the Vuex api doc page, and find in page for replaceState.

For Modules

IF you're replacing a store with modules you'll have to include empty state objects for each module. So, for example, if you have modules a and b, you'd do:

store.replaceState({
  a: {},
  b: {}
})
查看更多
放荡不羁爱自由
4楼-- · 2019-03-12 17:06

I am not sure what you use case is, but I had to do something similar. When a user logs out, I want to clear the entire state of the app - so I just did window.reload. Maybe not exactly what you asked for, but if this is why you want to clear the store, maybe an alternative.

查看更多
倾城 Initia
5楼-- · 2019-03-12 17:14

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
}

Reset Vuex Module State Like a Pro

Thanks to Taha Shashtari for the great solution.

Michael,

查看更多
爷的心禁止访问
6楼-- · 2019-03-12 17:14

Based on these 2 answers (#1 #2) I made a workable code.

My structure of Vuex's index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

import { header } from './header'
import { media } from './media'

Vue.use(Vuex)

const store = new Vuex.Store({
  plugins: [createPersistedState()],

  modules: {
    header,
    media
  }
})

export default store

Inside each module we need to move all states into separated var initialState and in mutation define a function resetState, like below for media.js:

const initialState = () => ({
  stateOne: 0,

  stateTwo: {
    isImportedSelected: false,
    isImportedIndeterminate: false,

    isImportedMaximized: false,
    isImportedSortedAsc: false,

    items: [],

  stateN: ...
  }
})

export const media = {
  namespaced: true,

  state: initialState, // <<---- Our States

  getters: {
  },

  actions: {
  },

  mutations: {
    resetState (state) {
      const initial = initialState()
      Object.keys(initial).forEach(key => { state[key] = initial[key] })
    },
  }

}

In Vue component we can use it like:

<template>
</template>

<script>
  import { mapMutations } from 'vuex'

  export default {
    name: 'SomeName',

    data () {
      return {
        dataOne: '',
        dataTwo: 2
      }
    },

    computed: {
    },

    methods: {
      ...mapMutations('media', [ // <<---- define module
        'resetState' // <<---- define mutation
      ]),

      logout () {
        this.resetState() // <<---- use mutation
        // ... any code if you need to do something here
      }
    },

    mounted () {
    }
  } // End of 'default'

</script>

<style>
</style>
查看更多
虎瘦雄心在
7楼-- · 2019-03-12 17:15

You can declare an initial state and reset it to that state property by property. You can't just do state = initialState or you lose reactivity.

Here's how we do it in the application I'm working on:

let initialState = {
    "token": null,
    "user": {}
}

const state = Vue.util.extend({}, initialState)

const mutations = {
    RESET_STATE(state, payload) {
       for (let f in state) {
        Vue.set(state, f, initialState[f])
       }
    }
}
查看更多
登录 后发表回答