API 参考
路由配置
| 属性 | 类型 | 说明 |
|---|---|---|
name | string | 路由名称 |
component | Component | 单个组件 |
components | Object | 命名视图组件映射 |
router-view 属性
| 属性 | 类型 | 说明 |
|---|---|---|
name | string | 视图名称,默认为 default |
router-link 属性
| 属性 | 类型 | 说明 |
|---|---|---|
to | string | object | 目标路由,可使用 { name: 'RouteName' } |
重定向
基本用法
通过 redirect 属性配置重定向:
javascript
const routes = [
{
path: '/home',
redirect: '/'
},
{
path: '/',
component: Home
}
]访问 /home 时,URL 会变成 /,并渲染 Home 组件。
重定向方式
1. 字符串形式
javascript
const routes = [
{
path: '/old-path',
redirect: '/new-path'
}
]2. 命名路由
javascript
const routes = [
{
path: '/old-path',
redirect: { name: 'Home' }
},
{
path: '/',
name: 'Home',
component: Home
}
]3. 函数形式
javascript
const routes = [
{
path: '/search/:keyword',
redirect: to => {
// to 是目标路由对象
// 返回重定向的目标路径或对象
return { path: '/result', query: { q: to.params.keyword } }
}
}
]访问 /search/vue 时,重定向到 /result?q=vue。
重定向到嵌套路由
javascript
const routes = [
{
path: '/user',
component: User,
redirect: '/user/profile', // 重定向到默认子路由
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]访问 /user 时,重定向到 /user/profile。
默认子路由重定向
javascript
const routes = [
{
path: '/settings',
component: Settings,
children: [
{
path: '',
redirect: 'profile' // 相对路径
},
{
path: 'profile',
component: ProfileSettings
},
{
path: 'security',
component: SecuritySettings
}
]
}
]导航守卫中的重定向
javascript
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (!isAuthenticated()) {
next('/login') // 重定向到登录页
} else {
next()
}
}
}
]重定向示例
页面迁移
javascript
const routes = [
// 旧路由重定向到新路由
{ path: '/article', redirect: '/blog' },
{ path: '/article/:id', redirect: '/blog/:id' },
// 新路由
{ path: '/blog', component: BlogList },
{ path: '/blog/:id', component: BlogDetail }
]默认路由
javascript
const routes = [
// 访问根路径重定向到首页
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home }
]带参数的重定向
javascript
const routes = [
{
path: '/user/:id',
redirect: to => {
return {
name: 'UserDetail',
params: { id: to.params.id }
}
}
}
]别名
基本用法
使用 alias 属性配置别名:
javascript
const routes = [
{
path: '/home',
component: Home,
alias: '/' // 别名
}
]访问 / 或 /home 都会渲染 Home 组件,但 URL 不会改变。
多个别名
javascript
const routes = [
{
path: '/home',
component: Home,
alias: ['/', '/index', '/main'] // 多个别名
}
]访问 /、/index、/main 或 /home 都会渲染 Home 组件。
嵌套路由的别名
javascript
const routes = [
{
path: '/user',
component: User,
alias: '/u', // 父路由别名
children: [
{
path: 'profile',
component: UserProfile,
alias: ['info', 'me'] // 子路由别名
}
]
}
]访问路径对应:
| URL | 渲染组件 |
|---|---|
/user | User |
/u | User(别名) |
/user/profile | User → UserProfile |
/user/info | User → UserProfile(别名) |
/user/me | User → UserProfile(别名) |
/u/profile | User → UserProfile |
/u/info | User → UserProfile(别名) |
带参数的别名
javascript
const routes = [
{
path: '/user/:id',
component: UserDetail,
alias: ['/u/:id', '/member/:id'],
props: true
}
]访问 /user/123、/u/123、/member/123 都会渲染 UserDetail 组件。
重定向 vs 别名对比
URL 变化对比
javascript
const routes = [
// 重定向:URL 会改变
{ path: '/a', redirect: '/b' },
{ path: '/b', component: B },
// 别名:URL 不改变
{ path: '/c', component: C, alias: '/d' }
]| 访问路径 | 最终 URL | 渲染组件 |
|---|---|---|
/a | /b | B(重定向,URL 改变) |
/c | /c | C |
/d | /d | C(别名,URL 不变) |
使用场景对比
重定向适用场景
- 页面迁移:旧 URL 重定向到新 URL
- 默认路由:访问父路由时重定向到默认子路由
- 权限控制:未登录时重定向到登录页
- URL 规范化:统一 URL 格式
别名适用场景
- 短路径访问:为长路径提供短别名
- 兼容旧路径:保持旧路径可访问
- 多入口访问:同一页面的多个访问路径
- SEO 优化:同一内容多个 URL
实际对比示例
javascript
const routes = [
// 重定向示例
{
path: '/old-about',
redirect: '/about',
// 用户访问 /old-about → URL 变成 /about
},
// 别名示例
{
path: '/about',
component: About,
alias: '/info',
// 用户访问 /info → URL 保持 /info,渲染 About 组件
}
]实战案例
案例 1:页面迁移重定向
javascript
const routes = [
// 旧路由重定向到新路由
{
path: '/posts',
redirect: '/blog'
},
{
path: '/posts/:id',
redirect: '/blog/:id'
},
{
path: '/posts/:id/comments',
redirect: '/blog/:id/comments'
},
// 新路由
{
path: '/blog',
name: 'BlogList',
component: () => import('@/views/blog/List.vue')
},
{
path: '/blog/:id',
name: 'BlogDetail',
component: () => import('@/views/blog/Detail.vue'),
props: true
},
{
path: '/blog/:id/comments',
name: 'BlogComments',
component: () => import('@/views/blog/Comments.vue'),
props: true
}
]案例 2:短路径别名
javascript
const routes = [
// 用户相关
{
path: '/user/:id',
component: UserDetail,
alias: ['/u/:id'],
props: true
},
// 产品相关
{
path: '/product/:id',
component: ProductDetail,
alias: ['/p/:id', '/item/:id'],
props: true
},
// 搜索
{
path: '/search',
component: Search,
alias: ['/s', '/find']
}
]案例 3:管理后台默认路由
javascript
const routes = [
{
path: '/admin',
component: AdminLayout,
redirect: '/admin/dashboard', // 默认重定向
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/admin/Dashboard.vue')
},
{
path: 'user',
redirect: 'user/list', // 子路由默认重定向
children: [
{
path: 'list',
component: () => import('@/views/admin/user/List.vue')
},
{
path: 'detail/:id',
component: () => import('@/views/admin/user/Detail.vue')
}
]
}
]
}
]案例 4:条件重定向
javascript
const routes = [
{
path: '/dashboard',
redirect: to => {
// 根据用户角色重定向到不同页面
const role = store.state.user.role
if (role === 'admin') {
return '/admin/dashboard'
} else if (role === 'user') {
return '/user/home'
}
return '/login'
}
}
]案例 5:动态参数重定向
javascript
const routes = [
{
// 旧格式:/user-123 重定向到 /user/123
path: '/user-:id(\\d+)',
redirect: to => {
return {
name: 'UserDetail',
params: { id: to.params.id }
}
}
},
{
path: '/user/:id',
name: 'UserDetail',
component: UserDetail,
props: true
}
]高级技巧
1. 重定向保留查询参数
javascript
const routes = [
{
path: '/old-search',
redirect: to => {
return {
path: '/search',
query: to.query // 保留查询参数
}
}
},
{
path: '/search',
component: Search
}
]访问 /old-search?q=vue&page=1 重定向到 /search?q=vue&page=1。
2. 重定向保留 Hash
javascript
const routes = [
{
path: '/old-article',
redirect: to => {
return {
path: '/article',
hash: to.hash // 保留 hash
}
}
}
]访问 /old-article#comments 重定向到 /article#comments。
3. 重定向链
javascript
const routes = [
{ path: '/a', redirect: '/b' },
{ path: '/b', redirect: '/c' },
{ path: '/c', component: C }
]注意
避免重定向循环,Vue Router 会检测并报错。
4. 导航守卫与重定向
javascript
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (!hasPermission('admin')) {
next({ name: 'Forbidden' }) // 重定向
} else {
next()
}
}
}
]5. 别名与路由元信息
javascript
const routes = [
{
path: '/admin',
component: Admin,
alias: '/manage',
meta: { requiresAuth: true, title: '管理后台' }
// 别名共享相同的 meta 信息
}
]最佳实践
1. 使用重定向处理旧 URL
javascript
// ✅ 推荐:保留旧 URL 的兼容性
const routes = [
{ path: '/old-path', redirect: '/new-path' },
{ path: '/new-path', component: NewComponent }
]
// ❌ 不推荐:直接删除旧路由
const routes = [
{ path: '/new-path', component: NewComponent }
// 用户访问 /old-path 会 404
]2. 使用别名提供短路径
javascript
const routes = [
{
path: '/user/profile/settings',
component: UserSettings,
alias: ['/settings', '/account'] // 提供短路径
}
]3. 默认子路由重定向
javascript
const routes = [
{
path: '/user',
component: User,
redirect: '/user/profile', // 明确指定默认子路由
children: [
{ path: 'profile', component: UserProfile },
{ path: 'posts', component: UserPosts }
]
}
]4. 避免重定向循环
javascript
// ❌ 错误:重定向循环
const routes = [
{ path: '/a', redirect: '/b' },
{ path: '/b', redirect: '/a' }
]
// ✅ 正确:避免循环
const routes = [
{ path: '/a', redirect: '/c' },
{ path: '/b', redirect: '/c' },
{ path: '/c', component: C }
]5. 使用命名路由重定向
javascript
// ✅ 推荐:使用命名路由
{ path: '/old', redirect: { name: 'New' } }
// ❌ 不推荐:硬编码路径
{ path: '/old', redirect: '/new-path' }常见问题
1. 重定向后如何获取原始 URL?
javascript
// 在重定向后的组件中
this.$route.redirectedFrom // 原始路由对象
this.$route.redirectedFrom?.path // 原始路径2. 重定向会影响导航守卫吗?
重定向会触发导航守卫,执行顺序:
- 失活组件的
beforeRouteLeave - 全局
beforeEach - 重定向路由的守卫
- 全局
beforeResolve - 全局
afterEach
3. 别名和重定向哪个更适合 SEO?
- 别名:同一内容有多个 URL,需要使用
canonical标签指定主 URL - 重定向:301 永久重定向更适合 SEO,告诉搜索引擎页面已迁移
4. 如何批量配置重定向?
javascript
// 批量重定向配置
const redirects = [
{ from: '/old-about', to: '/about' },
{ from: '/old-contact', to: '/contact' },
{ from: '/old-blog', to: '/blog' }
]
const routes = [
...redirects.map(r => ({
path: r.from,
redirect: r.to
})),
// 正常路由...
{ path: '/about', component: About },
{ path: '/contact', component: Contact },
{ path: '/blog', component: Blog }
]5. 别名支持嵌套吗?
别名自动继承父路由的别名:
javascript
const routes = [
{
path: '/user',
alias: '/u',
children: [
{
path: 'profile',
component: UserProfile
}
]
}
]
// 访问路径:
// /user/profile
// /u/profile(继承父别名)调试技巧
查看重定向来源
javascript
// 全局后置钩子
router.afterEach((to, from) => {
if (to.redirectedFrom) {
console.log('重定向来源:', to.redirectedFrom.path)
console.log('当前路径:', to.path)
}
})检查别名配置
javascript
// 获取路由配置
const route = router.options.routes.find(r => r.path === '/user')
console.log('别名配置:', route.alias)