Dynamic Routing | Vue Router - Add Routes on the Fly ๐ โ
Runtime route management - Extend your application's routing capabilities while it's running!
๐ฏ Overview โ
Dynamic routing allows you to add, remove, and modify routes while your Vue application is running. This powerful feature enables scenarios like plugin systems, feature toggles, and extensible applications where routing needs can change based on user interactions or external configurations.
๐ Key Functions โ
router.addRoute()- Add new routes dynamicallyrouter.removeRoute()- Remove existing routesrouter.hasRoute()- Check if a route existsrouter.getRoutes()- Get all route records
๐ก When to Use Dynamic Routing โ
๐ Application Scenarios โ
Plugin Systems
- Allow plugins to register their own routes
- Enable modular application architecture
- Support third-party extensions
Feature Toggles
- Show/hide routes based on feature flags
- A/B testing different route structures
- Gradual feature rollouts
User Permissions
- Dynamic route access based on user roles
- Conditional route availability
- Personalized navigation experiences
๐ ๏ธ Basic Usage Pattern โ
// Add a route dynamically
router.addRoute({
path: '/new-feature',
component: NewFeature,
name: 'new-feature'
})
// Remove a route by name
router.removeRoute('old-feature')๐ Getting Started โ
Example 1: Simple Route Addition โ
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home }
]
})
// Later in your application
function enableAdminPanel() {
router.addRoute({
path: '/admin',
component: () => import('./views/Admin.vue'),
name: 'admin'
})
// Navigate to the new route
router.push('/admin')
}Example 2: Conditional Route Loading โ
// Check user permissions and load appropriate routes
async function loadUserRoutes(user) {
if (user.isAdmin) {
router.addRoute({
path: '/admin',
component: () => import('./views/Admin.vue'),
children: [
{
path: 'users',
component: () => import('./views/AdminUsers.vue')
},
{
path: 'settings',
component: () => import('./views/AdminSettings.vue')
}
]
})
}
if (user.hasPremiumAccess) {
router.addRoute({
path: '/premium',
component: () => import('./views/Premium.vue')
})
}
}๐ง Advanced Techniques โ
Adding Nested Routes โ
You can add routes to existing parent routes by specifying the parent route name:
// Add nested route to existing parent
router.addRoute('admin', {
path: 'analytics',
component: () => import('./views/AdminAnalytics.vue')
})
// Equivalent to:
router.addRoute({
name: 'admin',
path: '/admin',
component: Admin,
children: [
{ path: 'analytics', component: AdminAnalytics }
]
})Route Removal Strategies โ
By Name (Recommended)
const removeRoute = router.addRoute({
path: '/temporary',
component: Temporary,
name: 'temporary'
})
// Remove by name
router.removeRoute('temporary')
// Or use the returned function
removeRoute()By Route Record
// Add route and store the record
const routeRecord = {
path: '/dynamic',
component: DynamicComponent,
name: 'dynamic'
}
router.addRoute(routeRecord)
// Later, remove it
router.removeRoute(routeRecord.name)๐ ๏ธ Practical Examples โ
Example 1: Feature Flag System โ
// feature-flags.js
export const featureFlags = {
newDashboard: true,
analytics: false,
premiumFeatures: true
}
// route-manager.js
export function setupDynamicRoutes(router) {
// Add routes based on feature flags
if (featureFlags.newDashboard) {
router.addRoute({
path: '/dashboard/new',
component: () => import('./views/NewDashboard.vue'),
name: 'new-dashboard'
})
}
if (featureFlags.analytics) {
router.addRoute({
path: '/analytics',
component: () => import('./views/Analytics.vue'),
name: 'analytics'
})
}
// Remove routes when flags are disabled
watch(featureFlags, (newFlags, oldFlags) => {
if (!newFlags.analytics && oldFlags.analytics) {
router.removeRoute('analytics')
}
})
}Example 2: Plugin System โ
// plugin-system.js
const registeredPlugins = new Map()
export function registerPlugin(pluginName, routes) {
if (registeredPlugins.has(pluginName)) {
console.warn(`Plugin ${pluginName} is already registered`)
return
}
// Store removal functions for each route
const removalFunctions = routes.map(route =>
router.addRoute(route)
)
registeredPlugins.set(pluginName, removalFunctions)
}
export function unregisterPlugin(pluginName) {
const removalFunctions = registeredPlugins.get(pluginName)
if (removalFunctions) {
removalFunctions.forEach(remove => remove())
registeredPlugins.delete(pluginName)
}
}๐ Navigation Considerations โ
Handling Current Location โ
When adding routes that match the current location, you may need to trigger a navigation:
router.addRoute({
path: '/about',
component: About
})
// If currently on /about, refresh the route
if (router.currentRoute.value.path === '/about') {
router.replace(router.currentRoute.value.fullPath)
}Navigation Guards โ
Routes added dynamically work with navigation guards:
router.addRoute({
path: '/protected',
component: Protected,
beforeEnter: (to, from) => {
if (!isAuthenticated()) {
return '/login'
}
}
})๐ Best Practices โ
โ Do โ
- Use Descriptive Names: Always name your routes for easy removal
- Clean Up: Remove routes when they're no longer needed
- Error Handling: Handle cases where routes might already exist
- Testing: Test dynamic route scenarios thoroughly
โ Don't โ
- Overuse: Don't make everything dynamic if static routes suffice
- Memory Leaks: Avoid adding routes without cleanup plans
- Complex Nesting: Keep dynamic route structures simple
- Race Conditions: Be careful with concurrent route modifications
๐ Related Features โ
- Route Meta Fields: Add metadata to dynamic routes
- Lazy Loading: Combine with dynamic imports for optimal performance
- Navigation Guards: Protect dynamically added routes
- Route Aliases: Create alternative paths for dynamic routes
๐ก Pro Tip
Combine dynamic routing with Vue's provide/inject API to create a powerful plugin system where different parts of your application can register their own routes!
Ready to build extensible applications? Start using dynamic routing to create flexible, adaptable Vue applications! ๐