Javascript is required
·
1 min read
·
1009 views

Vue Tip: Dynamically Add & Remove Route While App Is Running

Vue Tip: Dynamically Add & Remove Route While App Is Running Image

Adding routes to your router is usually done via the routes option, but in some situations, you might want to add or remove routes while the application is already running.

Vue Router provides two functions for dynamic routing: router.addRoute() and router.removeRoute()

Adding Routes

router.addRoute({ path: '/about', component: About })

Warning

addRoute only registers a new route. If you want to navigate to the newly added route, you need to manually navigate with router.push() or router.replace().

It's also possible to add nested routes:

1router.addRoute({ name: 'about', path: '/about', component: About })
2router.addRoute('about', { path: 'details', component: AboutDetails })

Removing Routes

There are three ways to remove an existing route:

  • Use router.removeRoute():
1router.addRoute({ path: '/about', component: About })
2router.removeRoute('about')
  • Use the callback returned by router.addRoute():
1const removeAboutRoute = router.addRoute({ path: '/about', component: About })
2removeAboutRoute() // removes the route if it exists
  • Add a route with a conflicting name. If you try to add a route with the same name as an existing route, it will remove the first route and add the new route:
1router.addRoute({ path: '/about', name: 'about', component: About })
2// this will remove the previously added route because they have the same name and names are unique
3router.addRoute({ path: '/other', name: 'about', component: Other })

The following StackBlitz contains a demo project for adding & removing routes:

Check the official documentation for more details about this feature.