4

I want to achieve n levels of dynamic nested routes in Vue.js, where n is unknown to me. for eg -

abc.com/ctx-path/component/1/2/...../n

where 1,2,...n are the levels

How can I achieve this with Vue-router?

Ayan Dalal
  • 69
  • 1
  • 3

3 Answers3

6

Behind the scenes vue-router path matching uses path-to-regexp. So it should be possible to write something like this

{ path: '/ctx-path/component/:id+', component: Component }

or

{ path: '/ctx-path/component/:id*', component: Component }

You could also add path dynamically at run time, but you'll need to have a trigger to add it.

One last option is to have a catch all route and add your own logic.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
  • What you are suggesting is use of wildcard for regex matching. But what i want is to open different pages for different routes. for eg: path: '/ctx-path/component/1/2/..../id1/.....n' & path: '/ctx-path/component/1/2/..../id2/.....n' should open 2 different pages. – Ayan Dalal Apr 03 '19 at 12:24
  • @Radu Diță Maybe you can hep me. Look at this : https://stackoverflow.com/questions/57836601/how-can-make-dynamyc-routes-on-the-vue-router – moses toh Sep 07 '19 at 23:16
0

This is from docs:

const router = new VueRouter({
    routes: [
        { path: '/user/:id', component: User,
            children: [
                {
                // UserProfile will be rendered inside User's <router-view>
                // when /user/:id/profile is matched
                path: 'profile',
                component: UserProfile
                },
                {
                // UserPosts will be rendered inside User's <router-view>
                // when /user/:id/posts is matched
                path: 'posts',
                component: UserPosts
                }
            ]
       }
   ]
})

see link https://router.vuejs.org/guide/essentials/nested-routes.html

Alex Nick
  • 44
  • 5
0

Double dynamic nested routes to filter a single view by the nested URL params

const routes = [
  {
    path: '/category/:categoryId',
    name: 'category',
    component: () =>
      import(/* webpackChunkName: "product" */ '../views/Categories.vue'),
    props: (route: Route) => ({
      categoryId: route.params.categoryId,
    }),
  },
  {
    path: '/category/:categoryId/:attributeIdsJsonString',
    name: 'attributeFilter',
    component: () =>
      import(/* webpackChunkName: "product" */ '../views/Categories.vue'),
    props: (route: Route) => ({
      categoryId: route.params.categoryId,
      attributeIdsJsonString: route.params.attributeIdsJsonString,
    }),
  },
];

const router = new VueRouter({
  routes,
});

Using different route names like this will mean that beforeRouteUpdate won't fire in some instances, so use beforeRouteEnter as well

ness-EE
  • 1,334
  • 13
  • 19