Using Vue 3 and Vuex 4, I was able to achieve this setup:
Let's assume we have a store structured like this:
https://i.sstatic.net/qBtrg.png
Our main store index.js (at the bottom) would look something like this:
import { createStore, createLogger } from 'vuex';
import module1 from '@/store/module1';
import module2 from '@/store/module2';
export default createStore({
modules: {
module1: module1,
module2: module2,
},
plugins: process.env.NODE_ENV !== 'production'
? [createLogger()]
: []
})
Each module would then have an index.js file like this:
import * as getters from './getters'
import * as actions from './actions'
import mutations from './mutations'
const state = {
postId: 10111,
}
export default {
namespaced: true,
state,
getters,
actions,
mutations,
}
The getter function in each module would be defined as follows:
export const getPostId = state => {
return state.postId
}
In a component, you can access the getters like this:
<template>
<div>
<div class="major_container">
<p>{{ postIdFromModule1 }}</p>
<p>{{ postIdFromModule2 }}</p>
</div>
</div>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
const postIdFromModule1 = computed(() => store.getters["module1/getPostId"]);
const postIdFromModule2 = computed(() => store.getters["module2/getPostId"]);
return {
postIdFromModule1,
postIdFromModule2,
};
},
};
</script>
Now, your modules are properly namespaced and ready for use!