in a nuxt.js app, I have nested routes like this:
route-1/route-2/route-3
I want to add an optional param after route-1
to render the same old route but with extra info(item id or something like that), which mean it will map to 2 route formats
route-1/:param/route-2/route-3
or route-1/route-2/route-3
without duplicate my folder structure
if I add a file with the param name it will be a required param and I will have to duplicate the folder structure without this param to handle the 2 scenarios
In my case solved with this. I have this pages tree:
pages/
--| search/
----| index.vue
--| index.vue
I need an optional 'category' param in the search page. I will to extend the routes like this:
// nuxt.config.js
export default {
router: {
middleware: [...],
extendRoutes (routes, resolve) {
routes.push({
name: 'search-category',
path: '/search/:category',
component: resolve(__dirname, 'pages/search/index.vue'),
chunkName: 'pages/search/_category/index'
})
}
}
}
If I navigate to /search
or /search/my-category
this render the same page in both cases, and in the second case I have the value my-category
in $route.params.category
:)
In your case, perhaps something like:
// nuxt.config.js
export default {
router: {
middleware: [...],
extendRoutes (routes, resolve) {
routes.push({
name: 'my-new-route',
path: '/route-1/:param/route-2/route-3',
component: resolve(__dirname, 'pages/same-route/index.vue'),
chunkName: 'pages/same-route/_param/index'
})
}
}
}
BTW: chunkName
is necessary if you use nuxtI18n
plugin, and after, in this plugin, the configuration for the dynamic route is (in my case):
// nuxt.config.js
export default {
i18n: {
pages: {
'search/index': { // <-- route in pages tree
es: '/buscar',
en: '/search'
},
'search/_category/index': { // <-- dynamic route configured
es: '/buscar/:category',
en: '/search/:category'
}
}
}
}
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