Skip to content

createRouter() | Vue Router

createRouter() is the main entry point for creating a Vue Router instance. This function initializes and configures the router with your application's routing setup. 🚀

📋 Function Signature

typescript
function createRouter(options: RouterOptions): Router

🎯 Purpose and Functionality

The createRouter() function is responsible for creating a fully configured router instance that manages your application's navigation state, route matching, and URL handling.

Key Responsibilities:

  • Route Configuration - Sets up your application's route definitions
  • History Management - Configures the history mode (HTML5, hash, or memory)
  • Navigation Guards - Enables route protection and validation
  • Scroll Behavior - Controls scrolling behavior during navigation

⚙️ Parameters

options - Router Configuration Object

PropertyTypeRequiredDescription
historyRouterHistoryHistory implementation (HTML5, hash, or memory)
routesRouteRecordRaw[]Array of route configuration objects
scrollBehaviorRouterScrollBehaviorCustom scroll behavior function

📤 Return Value

Returns a fully configured Router instance with methods for navigation, route matching, and state management.

💡 Basic Usage Example

Minimal Router Setup

javascript
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

export default router

Advanced Configuration

javascript
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('./views/Home.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login', 
      component: () => import('./views/Login.vue')
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

🔧 Advanced Configuration Options

Route Configuration

javascript
const router = createRouter({
  history: createWebHistory(),
  routes: [
    // Static route
    { path: '/', component: Home },
    
    // Dynamic route with parameters
    { path: '/user/:id', component: User },
    
    // Named route with alias
    { 
      path: '/about-us', 
      name: 'about',
      component: About,
      alias: '/company'
    },
    
    // Nested routes
    {
      path: '/admin',
      component: AdminLayout,
      children: [
        { path: 'dashboard', component: Dashboard },
        { path: 'users', component: UserManagement }
      ]
    }
  ]
})

Error Handling Configuration

javascript
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/:pathMatch(.*)*', component: NotFound }
  ]
})

// Global error handler
router.onError((error) => {
  console.error('Router error:', error)
})

🚨 Important Considerations

Router Instance Lifecycle

javascript
// Create router instance
const router = createRouter({ /* options */ })

// Use with Vue app
const app = createApp(App)
app.use(router)

// Router is now active and managing navigation
app.mount('#app')

TypeScript Support

typescript
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

📚 Best Practices

1. Route Organization

javascript
// Organize routes in separate files
import userRoutes from './routes/user'
import adminRoutes from './routes/admin'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    ...userRoutes,
    ...adminRoutes
  ]
})

2. Lazy Loading for Performance

javascript
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/dashboard',
      component: () => import('./views/Dashboard.vue') // Lazy loaded
    }
  ]
})

3. Environment-Specific Configuration

javascript
const isProduction = process.env.NODE_ENV === 'production'

const router = createRouter({
  history: isProduction ? createWebHistory() : createWebHashHistory(),
  routes: [
    // Development-only routes
    ...(isProduction ? [] : [
      { path: '/debug', component: DebugPanel }
    ])
  ]
})

💡 Pro Tip: Always use named routes when possible for better maintainability and to avoid hardcoded paths throughout your application.

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择