gpt4 book ai didi

javascript - 将 vuex 模块状态重置为某个初始状态值

转载 作者:行者123 更新时间:2023-11-28 03:07:02 24 4
gpt4 key购买 nike

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

我的基本商店如下:

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));
},

但运气不好......?

最佳答案

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

{ commit, dispatch, getters } as params

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

use this code inside the action "resetAllState"

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

关于javascript - 将 vuex 模块状态重置为某个初始状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com