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()
router.addRoute({ path: '/about', component: About })
addRouteonly 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 })
There are three ways to remove an existing route:
router.removeRoute():router.addRoute({ path: '/about', component: About })
router.removeRoute('about')
router.addRoute():const removeAboutRoute = router.addRoute({ path: '/about', component: About })
removeAboutRoute() // removes the route if it exists
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.
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 & Nuxt newsletter :
