How to clear state in vuex store?

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

    Myself has read above and implemented a solution. could help you as well!!

    All objects stored in Vue act as an observable. So if reference of a value is changed/mutated it triggers the actual value to be changed too.

    So, Inorder to reset the state the initial store modules has to be copied as a value.

    On logging out of an user, the same value has to be assigned for each modules as a copy.

    This can be achieved as following:

    Step 1: Create a copy of your initial module.

    // store.ts
    
    // Initial store with modules as an object
    export const initialStoreModules = {
        user,
        recruitment,
    };
    
    export default new Vuex.Store({
        /**
         * Assign the modules to the store 
         * using lodash deepClone to avoid changing the initial store module values
         */
        modules: _.cloneDeep(initialStoreModules),
        mutations: {
            // reset default state modules by looping around the initialStoreModules
            [types.RESET_STATE](state: any) {
            _.forOwn(initialStoreModules, (value: IModule, key: string) => {
                state[key] = _.cloneDeep(value.state);
            });
            },
        }
    });
    

    Step 2: Call the action to mutate the state to initial state.

    // user_action.ts
    const logout = ({ commit }: any) => {
        commit(types.LOGOUT_INIT);
        new UserProxy().logout().then((response: any) => {
          router.push({
            name: 'login',
          });
          // reset the state
          commit(types.RESET_STATE);
        }).catch((err: any) => {
          commit(types.LOGOUT_FAIL, err);
        });
    };
    

提交回复
热议问题