vue.jsvuexvuex-modules

Multiple vuex store in vue


I am trying to implement a micro frontend architecture in my application. I am having a common store where I have all the data which are commonly used across all the services. In one of the service I am trying to import the common store and use it globally, but I was not able to access it.

example:

in main.js I am trying the below code:

import Vue from "vue";
// Trying to import the common store
import commonStore from "../../common/src/store"
import router from "./router";
import store from "./store/store";

new Vue({
      router,
      store,
      commonStore
});

In App.vue i was trying to the below, but i am unable to access it.

mounted(){
  console.log(this.$commonStore);
}

Is there any way, I could use multiple stores in vue.


Solution

  • You are looking for Modules. In Vuex you can define independent store modules:

    const commonStore = {
      state: () => ({ a: 1 }),
    
    };
    
    const globalStore = {
      state: () => ({ a: 2 }),
    };
    
    const store = new Vuex.Store({
      modules: {
        commonStore: commonStore,
        globalStore: globalStore
      }
    })
    
    new Vue({
      router,
      store,
    });
    
    

    Then you can access module store via:

    mounted() {
      console.log(this.$store.state.commonStore.a); // => 1
      console.log(this.$store.state.globalStore.a); // => 2
    }