·
1 min read

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:

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 unique router.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.