Extend several new paths to a single page in Nuxt

Viewed 1546

I am struggeling with the nuxt folder/route structure for a project:

I want to achieve: All of them should show pages/data/index.vue:

www.example.com/data 
www.example.com/data/region
www.example.com/data/region/industry

And then access the parameter region or industry via the $route-class.

If I add _region folder and an _industy.vue it will show those files and I want to show and use the index.vue.

2 Answers

EDIT: Since region and industry are probably dynamic.
You could use this setup in your nuxt.config.js file

export default {
  router: {
    extendRoutes(routes, resolve) {
      routes.push(
        {
          name: 'data-region-industry',
          path: '/data/*/*',
          component: resolve(__dirname, 'pages/data/index.vue'),
        },
        {
          name: 'data-region',
          path: '/data/*',
          component: resolve(__dirname, 'pages/data/index.vue'),
        },
      )
    }
  }
}

With this configuration, you can go to either /data, /data/:region or /data/:region/:industry with only your index.vue file. No need to make some strange directories or file, you can keep all in one single place.

PS: the order is important. Put the most specific at top, otherwise /data/* will also catch /data/*/* and you'll never reach data-region-industry. This can be double-checked pretty quickly in the router tab of the Vue devtools.

This was taken from the official documentation: https://nuxtjs.org/docs/2.x/features/file-system-routing#extendroutes
I highly recommend giving it a read, especially if you are using Named views.


As for the URL catch, never heard of $route-class but you could make some kind of split on /, pretty doable!

you could use query in the url instead of params.

www.example.com/data 
www.example.com/data/?region=x
www.example.com/data/?region=x&?industry=y

you are still able to access the query data via $route.query. if you don't want to use query you have to manually overwrite vue router of nuxt as far as I know.

Related