vue 实现重定向请求
Vue 中实现请求重定向的方法
在 Vue 中实现请求重定向通常涉及前端路由(如 Vue Router)或 HTTP 请求拦截(如 Axios)。以下是两种常见场景的实现方式:
使用 Vue Router 进行路由重定向
通过 Vue Router 的导航守卫或路由配置实现页面跳转重定向:
// 在 router/index.js 中配置重定向
const routes = [
{
path: '/old-path',
redirect: '/new-path' // 直接重定向
},
{
path: '/protected',
component: ProtectedPage,
beforeEnter: (to, from, next) => {
const isAuthenticated = checkAuth() // 自定义认证逻辑
isAuthenticated ? next() : next('/login') // 条件重定向
}
}
]
全局前置守卫示例:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next({ path: '/login', query: { redirect: to.fullPath } })
} else {
next()
}
})
使用 Axios 拦截器实现 API 请求重定向
通过拦截 HTTP 响应处理 3xx 状态码或自定义逻辑:
// axios 响应拦截器
axios.interceptors.response.use(
response => response,
error => {
const { response } = error
if (response?.status === 401) {
window.location.href = '/login' // 强制页面跳转
// 或使用 Vue Router
router.push('/login')
}
return Promise.reject(error)
}
)
处理 302 重定向:
axios.get('/api/endpoint', {
maxRedirects: 0 // 禁止自动跟随重定向
}).catch(err => {
if (err.response?.status === 302) {
const redirectUrl = err.response.headers.location
window.location = redirectUrl // 浏览器跳转
}
})
服务端渲染(SSR)中的重定向
在 Nuxt.js 等 SSR 框架中使用 serverMiddleware 或 asyncData:
// Nuxt 中间件
export default function ({ redirect, route }) {
if (route.path === '/old') {
redirect(301, '/new')
}
}
注意事项
- 路由重定向不会改变浏览器 URL(客户端路由),HTTP 重定向会改变
- 对于 API 重定向,浏览器可能自动处理 3xx 状态码
- 在 SPA 中,外部 URL 重定向需使用
window.location - 考虑 SEO 影响,永久重定向建议使用 301 状态码
根据具体需求选择合适的方式,路由重定向适合前端导航控制,HTTP 重定向适合接口级跳转逻辑。







