Javascript is required
Mokkapps LogoMichael Hoffmann

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

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Dec 6, 2022
1 min read
|
82 views
Router
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:

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

Removing Routes

There are three ways to remove an existing route:

  • Use router.removeRoute():
router.addRoute({ path: '/about', component: About })router.removeRoute('about')
  • Use the callback returned by router.addRoute():
const removeAboutRoute = router.addRoute({ path: '/about', component: About })removeAboutRoute() // 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:
router.addRoute({ path: '/about', name: 'about', component: About })// this will remove the previously added route because they have the same name and names are uniquerouter.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.


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.