Search code examples
nuxt.jsvuex

Shared stores on multi applications Nuxt


I build multi-app Nuxt project, those apps don't communicate directly between them. Each app has own store and I want to use a directory for shared stores. I use this approach with components and that works fine.

|-> app1
|   |-> store // store app1
|   |   |-> moduleapp1.js
|   |-> components // component app1
|   |-> nuxt.config.js
|
|-> app2
|   |-> store // store app2
|   |   |-> moduleapp2.js
|   |-> components // component app2
|   |-> nuxt.config.js
|
|-> store // shared stores for all app
|   |-> shared_module_1.js
|   |-> shared_module_2.js
|-> components // components for all app, that works fine

Each app has a nuxt.config.js almost similar :

export default {
  srcDir: __dirname,
  buildDir: '.nuxt/app1',
  dir: {
    static: '../static/', //shared static
    assets: '../assets/', //shared assets
    //store: allow only a string, not Array 
  },
  plugins: [
    '../plugins/plugin_1', //own plugin
    './plugins/plugin_2', //shared plugin
  ],
  components: [
    '../components', //shared components
    {
      path: '../components/grid/', //shared components
      ignore: './filter/*.vue' //shared components

    },
    {path: './components/modal/', prefix: 'Modal'}, //own component
    {path: './components/nav/', prefix: 'Nav'}, //own component
  ]
}

https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-dir

Each app uses own and shared components also plugins and that works fine. But I don't find how I can do that with store, is it possible ?


Solution

  • Use plugin is the solution, like that :

    
    // plugin/loadStore.js
    // - List of shared stores
    import Grid from '../store/grid';
    import Map from '../store/map';
    import Sidebar from '../store/sidebar';
    
    export default ({isClient, store}) => {
    
      const opts = {}
      if (isClient) {
        opts.preserveState = true;
      }
    
      store.registerModule('grid', Grid, opts);
      store.registerModule('map', Map, opts);
      store.registerModule('sidebar', Sidebar, opts);
    };