When using modularization in Vuex, sometimes we need to access the state or getters of another module from one module. This can be achieved by utilizing the rootState and rootGetters parameters, which are available within getters, actions, and mutations inside a module.
Accessing Getters from Other Modules
Assume we have a Vuex store divided into two modules: moduleA and moduleB. If we want to access the getter of moduleB from moduleA, we can use the rootGetters parameter within the getter of moduleA.
Example
Assume our Vuex store structure is as follows:
javascriptconst moduleA = { state: () => ({ name: 'Alice' }), getters: { greeting: (state, getters, rootState, rootGetters) => { // Access the fullName getter of moduleB return `Hello, ${rootGetters['moduleB/fullName']}!`; } } }; const moduleB = { state: () => ({ firstName: 'Bob', lastName: 'Smith' }), getters: { fullName: (state) => { return `${state.firstName} ${state.lastName}`; } } }; const store = new Vuex.Store({ modules: { moduleA, moduleB } });
In the above code, we use rootGetters within the greeting getter of moduleA to access the fullName getter of moduleB. Note how we access it using the namespace (i.e., 'moduleB/fullName'). This is because each module operates within its own namespace, so specifying the module name is necessary to correctly access the desired getter.
Summary
Overall, by using rootGetters along with the module name prefix, we can access the state or getters of another module within a getter, action, or mutation of a module. This approach enhances inter-module interaction and flexibility, making Vuex's modularization more powerful and practical.