[Vuejs]-Creating Dynamic Routes from data NuxtJS

0👍

Check out the generate.routes function of the Nuxt config. This example is using the payload return property to speed things up.

const data = [
  {
    id: 1,
    make: 'Apple',
    model: 'iPhone 8',
    memory: 64
  },
  {
    id: 2,
    make: 'Apple',
    model: 'iPhone X',
    memory: 64
  },
  {
    id: 3,
    make: 'Samsung',
    model: 'S20',
    memory: 128
  }
]

export default {
  generate: {
    routes() {
      return data.map(item => ({
        route: `/${item.make}/${item.model}/${item.memory}`,
        payload: item
      }))
    }
  }
}

This will create a page for every configuration of make, model, and memory. To make a page just for each make, or just for each model, you just need to add additional { route, payload } objects for the pages you’d like. You’ll of course need page components set up to handle each route you return as well.

Then, inside your page component:

async asyncData ({ params, error, payload }) {
    if (payload) return { phone: payload }
    else return { phone: await backend.fetchPhone(params.make, params.model, params.memory) }
}

As of the last time I used this, it’s required to check for the payload property in asyncData due to the way Nuxt currently handles static generation. See this issue for an explanation.

Leave a comment