Preloading data to the store at startup in nuxt

Viewed 267

I am working on a app with Nuxt and I preload some stuff at nuxtServerInit and put it into the store. That's fine and there is no problem.

I have many more projects with the same kind of initial-preload - so I start thinking that's a good idea to put the logic into a module and all of my other projects can just add the module to the nuxt.config.js and the store will be prefilled... I started creating the module and find out, that there is no way to reach the store at this point, am I right?

I tried nuxt.hook('ready', (nuxt) => {...} but the nuxt-parameter from the callback doesn't have a store reference.

I am new at Nuxt and maybe I miss some point or handle my preload-issue the wrong way?

Here is my modules/mymodule.ts

const mymodule: Module<Options> = function (moduleOptions: Options) {
  const { nuxt } = this

  nuxt.hook('ready', async (__nuxt: any) => {
    // __nuxt ... no store reference :(
  })
}
export default mymodule
1 Answers

Vue 2 answer:

I had to do something similar. I think you should be looking for the store in moduleOptions.

In my instance, to access the store, I created a plugin.

// nuxt.conf.js

buildModules: [
    '@namespace/node_modules_route',
]

// plugin.js

// When initializing module in nuxt.config, only the plugin is moved 
// (not deps) so it doesn't resolve via relative import.
// SEE: https://github.com/nuxt/nuxt.js/issues/6169
import SomeStore from '@namespace/node_modules_route/store'

export default function ({ store }) {
  store.registerModule('cxl-session', SomeStore())
}

// module.js


module.exports = async function (moduleOptions) {
  const options = {
    ...this.options['my-plugin'],
    ...moduleOptions,
  }

  this.addPlugin({
    src: resolve(__dirname, 'plugin.js'),
    fileName: 'my-plugin.js',
    options,
  })
}

module.exports.meta = require('../package.json')
Related