4

I am trying to find out how to use the same page for multiple routes on a Nuxt.js with i18n module.

Basically I want this route: /product-category/:slug/in/:material to use the same page as /product-category/:slug

So far I have tried below, adding it to nuxt.config.js - but it doesn't work. It simply shows the _slug/_material/index.vue file.

router: {
    extendRoutes (routes, resolve) {
        routes.push({
            path: '/product-category/:slug/in/:material',
            component: resolve(__dirname, 'pages/product-category/_slug/index.vue')
        })
    }
},

Maybe because I am having the i18n module, maybe because I am doing something wrong.

This is my folder structure:

ed

If I inspect my router.js file, I see the path shown twice:

enter image description here

FooBar
  • 5,752
  • 10
  • 44
  • 93

2 Answers2

2

This was my workaround, I just wish there was a simpler method. Plus it still works if you use nuxt i18n.

nuxt.config.js

router: {
    extendRoutes (routes, resolve) {
        const routesToAdd = [
            { // add your routes here
                name: 'product-category-slug-material',
                path: '/product-category/:slug/in/:material',
                component: resolve(__dirname, 'pages/product-category/_slug/index.vue'), // which component should it resolve to?
                chunkName: 'pages/product-category/_slug/_material/index' // this part is important if you want i18n to work
            }
        ];

        const existingRoutesToRemove = routesToAdd.map(route => route.name);

        const generateRoutes = routes.filter((route) => {
            return !existingRoutesToRemove.includes(route.name);
        });

        routesToAdd.forEach(({ name, path, component, chunkName }) => {
            generateRoutes.push({
                name,
                path,
                component,
                chunkName
            });
        });

        routes.splice(0, routes.length, ...generateRoutes); // set new array
    }
},
FooBar
  • 5,752
  • 10
  • 44
  • 93
0

You can use _.vue to catch everything.

If you do not know the depth of your URL structure, you can use _.vue to dynamically match nested paths. This will handle requests that do not match a more specific request.

Here you can find out more.

husayt
  • 14,553
  • 8
  • 53
  • 81