In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules.
For instance, if I need the fileId
in two separate modules, I approach it like this:
// Common file id store:
export default {
state: {
fileId: '',
},
actions: {
setFileId({commit}, id) {
commit('mutateFileId', id);
},
},
mutations: {
mutateId(state, id) {
state.fileId = id;
},
},
};
I then import this module into other modules, for example:
// Store 1 where the file id is needed:
import fileIdModule from '@/store/modules/fileIdModule';
export default {
modules: {
fileIdModule,
},
actions: {
whatEver({commit, dispatch}, param) {
...
dispatch('setFileId', 1);
},
},
};
And in another store where the fileId is still required:
// Store 2 where the file id is needed:
import fileIdModule from '@/store/modules/fileIdModule';
export default {
modules: {
fileIdModule,
},
actions: {
whatEver2({commit, dispatch}, param2) {
...
dispatch('setFileId', 2);
},
},
};
The reason behind this approach is that the information is only necessary in a few stores out of many and as the application grows, importing duplicate modules can lead to issues...
However, one drawback of this method is that importing the same module multiple times can cause actions to be duplicated. For example, if I include the module in three places, the action will execute three times. This can be verified by adding a console.log
statement inside the action:
actions: {
setFileId({commit}, id) {
console.log('Mutating file id');
commit('mutateFileId', id);
},
},
Even triggering the action from just one module will result in the console.log
being printed twice.
Is there a way to share nested modules without causing duplication?