Vue Tip: Dynamically Add & Remove Route While App Is Running
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
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:
Removing Routes
There are three ways to remove an existing route:
- Use
router.removeRoute()
:
- Use the callback returned by
router.addRoute()
:
- 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:
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 X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Force-Enable Vue Devtools in Production Build
Usually, the Vue Devtool extension is disabled in production builds, but there is a way to force-enable it.
Vue Tip: Disable Attribute Inheritance
By default, parent scope attribute bindings that are not recognized as props will "fallthrough". This may not always be the desired behavior and, therefore, can be disabled. A typical use case is a component with multiple root nodes.