将vuex模块的状态重置为一些initialState值

时间:2020-03-04 11:58:46

标签: javascript vue.js vuex

我正在尝试提出一种可以将模块状态重置为初始值的方法,到目前为止,我还是遇到了一些概念性问题。

我的基本商店如下:

const store = new Vuex.Store({
  modules: {
    moduleA: moduleA,
  },
  actions: {
    resetAllState: ({ dispatch }) => {"moduleA");
    },
    resetModuleState: (currentModule) => {
      // Perform the reset here...somehow?
    }
  }
});

moduleA.js存储区的创建过程如下:intialState

const initialState = () => ({
   helloWorld: {}  
});

const moduleA = {
  namespaced: true,
  state: {
    initialState: initialState(),
    ...initialState(),
  }
};

export default moduleA;

因此,我利用散布运算符创建以下内容:

const moduleA = {
  namespaced: true,
  state: {
    initialState: initialState(),
    helloWord: {}
  }
};

然后我可以变异state.helloWorld,同时保留state.initialState ...的副本...

所以,我现在的问题是,在以下全球商店中

    resetModuleState: (currentModule) => {
      // Perform the reset here...somehow?
    }

操作,我该如何实际执行重置?

我把这当作全局重置状态的方法:

resetAllState: function() {
      let defaultState = {};
      Object.keys(store.state).forEach((key) => {
        defaultState = {
          ...defaultState,
          [key]: store.state[key].initialState ? store.state[key].initialState : store.state[key],
        };
      });
      store.replaceState(Object.assign({}, defaultState));
    },

可是没有运气...?

1 个答案:

答案 0 :(得分:0)

上面的代码有问题,操作只能访问

{ commit, dispatch, getters } as params

在上面的代码“ resetModuleState”中,第一个参数使用了modueleName,但是它将有一个对象,因此,可以通过以下方法直接访问模块对象,并通过从您拥有的每个模块中调用initialState()函数来重置stathe

在动作“ resetAllState”中使用此代码

resetAllState: function({ dispatch }) {
    this._modules.root.forEachChild((childModule) => {
      childModule.state.initialState();
    });
},