How to clear state in vuex store?

后端 未结 12 1273
既然无缘
既然无缘 2020-12-23 12:21

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?

12条回答
  •  一整个雨季
    2020-12-23 13:18

    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:

    
    
    
    
    
    

提交回复
热议问题