9

According to this official example, we have the ability to add nested/children routes in vuejs. But I cannot find any help/docs around a way to add these children routes dynamically. e.g only add child routes when Parent route is visited.

Currently all the routes in a Vue application are defined in a single place where we create Router instance. There is an api called addRoutes, but I don't know how to use that to add lazily loaded features of application along side their routes. If someone is familiar with Angular2+ Module system, that has this ability to define routes for the feature modules inside that module and even make them lazily loaded. Wondering if something could be achieved with VueJs?

Nexus23
  • 5,607
  • 8
  • 43
  • 64

1 Answers1

10

You can use $router.addRoutes to re-add a route, specifying children.

You'll need to get the current route definition (as opposed to the $route object) by searching the $router.options.routes array for the route definition object that matches the current $route.path. Then add a children array of route definitions to the object and pass it to $router.addRoutes.

created() {
  let { routes } = this.$router.options;
  let routeData = routes.find(r => r.path === this.$route.path);
  routeData.children = [
    { path: 'bar', component: Bar },
    { path: 'baz', component: Baz },      
  ];
  this.$router.addRoutes([routeData])
}

Here's an example fiddle of dynamically adding child routes in the created hook of a route's component definition.

Ben Everard
  • 13,254
  • 12
  • 63
  • 95
thanksd
  • 44,567
  • 20
  • 126
  • 130
  • 4
    thanks for your answer. One last piece of the puzzle. It works when we usually navigate on the client side but it breaks when do the full reload on child path. Full realod ended up in 404. – Nexus23 Feb 17 '18 at 12:52
  • Is there any solution to full reload on child path(f5) in December 2018. – Sandeep sandy Dec 05 '18 at 06:29
  • 3
    Still no way of persisting this data via page refresh. Vue router really needs this functionality if it wants to go up against the likes of React Router. – Evan Burbidge Dec 17 '18 at 23:20
  • 1
    The router is reactive, so even a missing route can work after a full reload, if the route is subsequently added to the page. This should work unless there's a `*` route with redirect. See https://codesandbox.io/s/vue-dynamic-components-owhwr – Alex Gyoshev Oct 01 '19 at 14:23