Home > Software design >  Nuxt Generate dynamic routes from the store
Nuxt Generate dynamic routes from the store

Time:11-29

I'm using nuxt.js and now need to generate my dynamic pages by running npm run generate. However my list items needed to make dynamic items are stored in the store, so I need to map over them somehow so the generate can make the routes for them

How can I access the store in my nuxt.config.js?

generate: {
  dir: 'wwwroot', //override the default generation dir to create everything straight in wwwroot
  routes() {
    let vdc = this.$store.vdcServers.map(server => `/virtual-data-centres/${server.slug}`);
    return Promise.all([vdc]).then(values => {
      return values.join().split(',');
    })
  }
}

Output

 ERROR  Could not resolve routes                                                                        
 FATAL  Cannot read properties of undefined (reading '$store')   

CodePudding user response:

To my knowledge, you cannot access the store from that place. Maybe with some hooks? I doubt.
Meanwhile, if you have your elements available in your store you should be able to find them back by making a quick axios call or like I think.

This kind of approach is totally fine

import axios from 'axios'

export default {
  generate: {
    routes(callback) {
      axios
        .get('https://my-api/users')
        .then(res => {
          const routes = res.data.map(user => {
            return '/users/'   user.id
          })
          callback(null, routes)
        })
        .catch(callback)
    }
  }
}

It may be a bit of code duplication, meanwhile, it's still the simplest way to go.
Otherwise, you could try to persist it to some localStorage or any similar solution, to have it both in Vuex and during your generation.

  • Related