createRouter | Vue Router API
概述
createRouter 是 Vue Router 的核心函数,用于创建路由器实例。它是构建单页应用程序路由系统的起点。
语法
typescript
function createRouter(options: RouterOptions): Router参数
RouterOptions 对象
typescript
interface RouterOptions {
history: RouterHistory
routes: RouteRecordRaw[]
scrollBehavior?: RouterScrollBehavior
parseQuery?: (query: string) => Record<string, any>
stringifyQuery?: (query: Record<string, any>) => string
linkActiveClass?: string
linkExactActiveClass?: string
}基本用法
创建基础路由器
javascript
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
// 在应用中使用
app.use(router)完整配置示例
javascript
const router = createRouter({
// 必需:历史模式
history: createWebHistory(),
// 必需:路由配置
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/users/:id', component: UserDetail }
],
// 可选:滚动行为
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
return { top: 0 }
},
// 可选:链接激活类名
linkActiveClass: 'router-link-active',
linkExactActiveClass: 'router-link-exact-active'
})配置选项详解
history
类型: RouterHistory必需: 是 说明: 指定路由器的历史模式
javascript
// HTML5 历史模式(推荐)
history: createWebHistory()
// 哈希模式
history: createWebHashHistory()
// 内存历史模式(测试用)
history: createMemoryHistory()routes
类型: RouteRecordRaw[]必需: 是 说明: 路由配置数组
javascript
routes: [
// 基础路由
{ path: '/', component: Home },
// 命名路由
{ path: '/user/:id', name: 'user', component: User },
// 嵌套路由
{
path: '/admin',
component: AdminLayout,
children: [
{ path: 'users', component: UserList }
]
},
// 重定向
{ path: '/home', redirect: '/' },
// 别名
{ path: '/', component: Home, alias: '/home' }
]scrollBehavior
类型: RouterScrollBehavior必需: 否 说明: 控制导航时的滚动行为
javascript
scrollBehavior(to, from, savedPosition) {
// 返回顶部
if (to.hash) {
return { el: to.hash, behavior: 'smooth' }
}
// 恢复位置(浏览器前进后退)
if (savedPosition) {
return savedPosition
}
// 默认行为
return { top: 0 }
}linkActiveClass / linkExactActiveClass
类型: string必需: 否 说明: 自定义 RouterLink 激活状态的 CSS 类名
javascript
linkActiveClass: 'active-link',
linkExactActiveClass: 'exact-active-link'高级用法
自定义查询参数处理
javascript
const router = createRouter({
history: createWebHistory(),
routes: [...],
// 自定义查询参数解析
parseQuery(queryString) {
return Object.fromEntries(
new URLSearchParams(queryString)
)
},
// 自定义查询参数序列化
stringifyQuery(query) {
return new URLSearchParams(query).toString()
}
})组合式 API 使用
javascript
import { createRouter, createWebHistory } from 'vue-router'
export function useRouterSetup() {
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
return { router }
}实际应用场景
场景 1:企业级应用配置
javascript
import { createRouter, createWebHistory } from 'vue-router'
// 路由配置
const routes = [
{
path: '/',
name: 'dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'login',
component: () => import('@/views/Login.vue'),
meta: { guestOnly: true }
}
]
// 创建路由器
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
// 企业级滚动行为
if (to.hash) {
return {
el: to.hash,
behavior: 'smooth',
top: 80 // 考虑导航栏高度
}
}
if (savedPosition) {
return savedPosition
}
return { top: 0, behavior: 'smooth' }
}
})
export default router场景 2:多语言路由
javascript
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/:lang',
component: Layout,
beforeEnter(to) {
// 验证语言参数
const lang = to.params.lang
if (!['en', 'zh', 'ja'].includes(lang)) {
return '/en' // 默认重定向到英文
}
},
children: [
{ path: '', component: Home },
{ path: 'about', component: About }
]
}
]
})场景 3:微前端路由配置
javascript
// 主应用路由器
const mainRouter = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: MainApp },
{ path: '/micro-app/*', component: MicroAppContainer }
]
})
// 微应用独立路由器
const microRouter = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component: MicroHome },
{ path: '/settings', component: MicroSettings }
]
})最佳实践
1. 路由配置模块化
javascript
// routes/index.js
import userRoutes from './user'
import adminRoutes from './admin'
import publicRoutes from './public'
export default [
...publicRoutes,
...userRoutes,
...adminRoutes
]
// main.js
import routes from './routes'
const router = createRouter({
history: createWebHistory(),
routes
})2. 环境特定配置
javascript
const routerConfig = {
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior: process.env.NODE_ENV === 'production'
? productionScrollBehavior
: developmentScrollBehavior
}
const router = createRouter(routerConfig)3. 错误处理
javascript
try {
const router = createRouter({
history: createWebHistory(),
routes: validateRoutes(routes) // 验证路由配置
})
} catch (error) {
console.error('路由器创建失败:', error)
// 提供降级方案
const router = createRouter({
history: createWebHistory(),
routes: getFallbackRoutes()
})
}注意事项
- 单例模式 - 每个应用应该只有一个路由器实例
- 路由验证 - 在生产环境验证路由配置
- 性能考虑 - 大型路由配置考虑代码分割
- 类型安全 - 使用 TypeScript 增强类型检查
兼容性
- Vue 3.0+
- 现代浏览器支持
- SSR 兼容
🎯 总结:
createRouter是 Vue Router 的基石,合理配置可以构建出强大而灵活的路由系统。通过理解各个配置选项的作用,你可以创建出符合项目需求的定制化路由解决方案。