在 Vue3 中使用 Vue Router 进行重定向是常见需求,以下是详细指南:
一、Vue3 重定向基础
在 router.js
中通过 redirect
属性实现:
const routes = [
{
path: '/old',
redirect: '/new' // 直接跳转
},
{
path: '/dynamic-redirect',
redirect: to => { // 动态重定向
return { path: '/target' }
}
}
]
二、5 大常见场景及实现
1. 静态路径重定向
{ path: '/legacy-page', redirect: '/modern-page' }
2. 动态参数保留
{
path: '/user/:id',
redirect: '/profile/:id' // 自动保留参数
}
3. 条件重定向(路由守卫)
router.beforeEach((to, from, next) => {
if (需要登录的页面 && 未登录) {
next('/login')
} else {
next()
}
})
4. 查询参数重定向
// 从 /search?q=vue 重定向到 /results?query=vue
{
path: '/search',
redirect: to => ({
path: '/results',
query: { query: to.query.q }
})
}
5. 404 兜底重定向
{ path: '/:pathMatch(.*)*', redirect: '/not-found' }
三、3 个常见问题及解决方案
1. 无限重定向循环
现象:ERR_TOO_MANY_REDIRECTS
错误
原因:守卫逻辑或重定向路径循环
解决:
// 错误示例:登录页无限重定向
router.beforeEach((to, from, next) => {
if (to.path === '/login' && isLoggedIn) {
next('/') // 这将导致循环
}
})
// 正确写法:添加终止条件
router.beforeEach((to, from, next) => {
if (to.path === '/login' && isLoggedIn) {
if (from.path === '/login') {
next('/')
} else {
next(false) // 中止导航
}
}
})
2. 路由参数丢失
现象:重定向后 URL 参数丢失
解决:使用函数形式保留参数
{
path: '/shop',
redirect: to => ({
path: '/store',
query: to.query // 保留原始查询参数
})
}
3. 哈希路由异常
现象:带 hash 的路由重定向失败
解决:明确处理 hash
{
path: '/old#section',
redirect: to => ({
path: '/new',
hash: '#segment'
})
}
四、最佳实践
-
优先级控制
路由按顺序匹配,通配符路由 (*
) 必须放在最后 -
导航守卫优化
// 使用 return 代替 next() 更安全
router.beforeEach((to, from) => {
if (需要重定向条件) {
return '/target-path'
}
})
- TypeScript 类型提示
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
// 获得完整类型检查
]
- 服务端配合
对于 SEO 敏感页面,应在服务器层配置 301 重定向(如 Nginx)
location /old-page {
return 301 https://yoursite.com/new-page;
}
五、Composition API 示例
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
// 编程式重定向
function handleRedirect() {
router.push({
path: '/target',
query: { ref: 'fromComponent' }
})
}
</script>
总结建议
- 简单重定向:优先使用静态配置
- 复杂逻辑:使用函数式重定向或导航守卫
- 重要路径:服务器端配置真实 301 重定向
- 测试阶段:使用
router.resolve()
方法验证重定向路径
通过合理运用这些方案,可以解决 Vue3 项目中 95% 以上的重定向需求,同时避免常见陷阱。