I am having a fairly easy problem.
In my nuxt app I want to display a list of items based on objects in an array in a simple .json file. Furthermore when the specific item is clicked I want to show a detailed view of that item with more data. Imagine it is a list about cars, a dynamic route would look like: "cars/ford-500".
Now if I populate a vuex variable and display that in the dynamic route component - I dont get the SEO benefits since its loaded by the client. Furthermore if I want to refresh the page with the dynamic link I get an error because the store is deleted after refresh. Another option is passing a route parameter but then again on refresh I get the error.
Basically I dont want to create 100 html pages I just want to let nuxt-generate do it automatically with my .json file and I want to display the specific data for that list item when I reload the dynamic route. I know nuxt-generate does not look at dynamic paths but there is a nuxt-generate property in the config file one can use to tell them to loop through.
Thank you so much for your help!
If you want Nuxt.js to generate routes with dynamic params, you need to set the generate.routes property to an array of dynamic routes.
If you have a list with the urls you can do it like so:
// nuxt.config.js
generate {
routes () {
// You can also import this from a js file.
const yourUrls = ['ford-500', 'porche-spyder', 'mclaren-senna', 'volkswagen-beetle'];
const routesToGenerate = [];
for (const url of yourUrls) {
const newRoute = '/cars/' + url;
routesToGenerate.push(newRoute);
}
return routesToGenerate;
}
}
Of course you can use a .json file as well
// nuxt.config.js
generate {
routes () {
const routesToGenerate = [];
for (const urlKey of Object.keys(yourJsonFile)) {
const newRoute = '/cars/' + yourJsonFile[urlKey];
routesToGenerate.push(newRoute);
}
return routesToGenerate;
}
}
If you need to you can also pass payload into the component you're generating. You can read more about it in the documentation here. (https://nuxtjs.org/api/configuration-generate/#routes)
If you are using an internationalization module like nuxt-i18n you'll need to manually define the locale prefix
// nuxt.config.js
generate {
routes () {
// You can also import this from a js file.
const yourUrls = ['ford-500', 'porche-spyder', 'mclaren-senna', 'volkswagen-beetle'];
const yourLocales = ['da-DK', 'en', 'de']
const routesToGenerate = [];
for (const url of yourUrls) {
const defaultRoute = '/cars/' + url;
routesToGenerate.push(defaultRoute);
for (const locale of yourLocales) {
const localeRoute = locale + '/cars/' + url;
routesToGenerate.push(localeRoute);
}
}
return routesToGenerate;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With