'Is it possible to inject a vuex store depending on the route?

The app I'm working on has multiple stores with modules inside. I would like to inject the store globally depending on the path route. Is this possible to do?

import VueRouter from 'vue-router';
import Vuex from 'vuex';
Vue.use(VueRouter);
Vue.use(Vuex);

const router = new VueRouter({
routes: [
{ path:"/", component:Homepage},
{ path:"/Site", component:Sitepage}
], mode: 'history');

 new Vue({router, store }).$mount('#app');

I have each store in a list, e.g. stores = [HomepageStore, SitepageStore];

I tried combining the individual stores and making a whole store from it like this:

const store = new Vuex.Store({
  modules: {
    HomepageStore, SitepageStore
  }
});

This shows a blank page with no errors, even though it shows the store data and the routes, it doesn't show any elements on the page. It doesn't help it already has modules inside. There are about 50 store files so I do not want to alter each one in case. Any help would be much appreciated.

Just to update I am using vue 2.6.12 and vue-router 3.1.6



Solution 1:[1]

https://vuex.vuejs.org/guide/modules.html

I think your formatting isn't correct please try

const store = new Vuex.Store({
  modules: {
    homepageStore: HomepageStore, 
    sitepageStore: SitepageStore
  }
});

Accessing your stores can then be done with

this.$store.state.homepageStore....
this.$store.state.sitepageStore....

Or you could create a global variable that has multiple stores

window._globalStore = stores;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joeri