Vuex:在动作中引用模块变量 [英] Vuex: referencing the modules variable inside action
问题描述
我的 Vue 应用程序中有以下全局存储:
I have the following global store within my Vue application:
// N.B. These Stores Are Modularised, please reference: [https://vuex.vuejs.org/guide/modules.html] for details.
const store = new Vuex.Store({
modules: {
surfers: surfers,
surfSites: surfSites,
surfTickets: surfTickets
},
actions: {
resetAllState: ({ dispatch, modules }) => {
console.log(modules); // Undefined
console.log(store.modules); // Undefined
console.log(this.modules); // Error in v-on handler: "TypeError: _this is undefined"
for (const currentModule in modules) {
console.log(`Resetting Module State: ${module}`);
if (modules[currentModule].state.hasOwnProperty("initialState")) {
dispatch("resetModuleState", currentModule);
}
}
},
resetModuleState: (currentModule) => {
console.log(`Resetting Module State: ${currentModule}`);
}
}
});
我的目标是这些动作将在模块中循环,并发送一个重置状态动作,当我注销当前用户时调用它.
My aim is that the actions will cycle through the modules, and dispatch off a reset state action, which I call when I log the current user out.
然而,modules
是未定义的,store.modules
和 this.modules
都是未定义的或通过未定义的相关错误...
However, modules
is undefined, store.modules
and this.modules
are all undefined or through an undefined related error...
那么,如果可能的话,我该如何以这种方式动态访问模块?
So, how do I go about accessing modules dynamically in this way, if at all possible?
推荐答案
以上代码有问题,actions只能访问
The above code is having issue, the actions can have only access to
{ commit, dispatch, getters } as params
但是您尝试在参数中传递模块,但您仍然可以通过以下方法访问模块
but you tried to pass modules in the params, but still you can access to the modules by below approach
在操作resetAllState"中使用此代码
use this code inside the action "resetAllState"
resetAllState: function ({ dispatch }) {
for (const currentModule in modules) {
this._modules.root.forEachChild((childModule) => {
console.log(childModule);
});
//if (modules[currentModule].state.hasOwnProperty("initialState")) {
// dispatch("resetModuleState", currentModule);
//}
}
},
这篇关于Vuex:在动作中引用模块变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!