问题
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.
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?
回答1:
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
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);
//}
}
},
来源:https://stackoverflow.com/questions/60525082/vuex-referencing-the-modules-variable-inside-action