Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an optional param in nested routes in Nuxt.js?

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

like image 984
Mahmoud Zohdi Avatar asked Oct 16 '22 06:10

Mahmoud Zohdi


1 Answers

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'
      }
    }
  }
}
like image 92
lmfresneda Avatar answered Dec 21 '22 15:12

lmfresneda