How to clear state in vuex store?

后端 未结 12 1272
既然无缘
既然无缘 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 12:53

    Here's a solution that works in my app. I created a file named defaultState.js.

    //defaultState.js
    //the return value is the same as that in the state
    const defaultState = () => {
        return {
           items: [],
           poles: {},
           ...
        }
    }
    
    export default defaultState
    

    And then Where you want to use it

    //anywhere you want to use it
    //for example in your mutations.js
    //when you've gotten your store object do
    
    import defaultState from '/path/to/defaultState.js'
    
    let mutations = {
        ...,
        clearStore(state){
            Object.assign(state, defaultState())
        },
    }
    
    export default mutations
    
    

    Then in your store.js

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    import actions from './actions';
    import getters from './getters';
    import mutations from './mutations'; //import mutations
    import state from './state';
    
    Vue.use(Vuex);
    
    
    export default new Vuex.Store({
        actions,
        mutations,
        state,
        getters,
    });
    
    

    and That's it

提交回复
热议问题