Skip to content

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 dynamically
  • router.removeRoute() - Remove existing routes
  • router.hasRoute() - Check if a route exists
  • router.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 โ€‹

javascript
// 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 โ€‹

javascript
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 โ€‹

javascript
// 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:

javascript
// 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)

javascript
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

javascript
// 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 โ€‹

javascript
// 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 โ€‹

javascript
// 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:

javascript
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)
}

Routes added dynamically work with navigation guards:

javascript
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
  • 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! ๐Ÿš€

๐Ÿš€ Vue Router - ่ฎฉๅ‰็ซฏ่ทฏ็”ฑๅ˜ๅพ—็ฎ€ๅ•่€Œๅผบๅคง | ๆž„ๅปบ็ŽฐไปฃๅŒ–ๅ•้กตๅบ”็”จ็š„ๆœ€ไฝณ้€‰ๆ‹ฉ