vue实现页面重定向
路由重定向(Vue Router)
在Vue项目中,通过Vue Router的redirect配置实现页面跳转,适用于全局路由规则。修改router/index.js文件:
const routes = [
{
path: '/old-path',
redirect: '/new-path' // 简单重定向
},
{
path: '/dynamic-redirect',
redirect: to => {
// 动态返回重定向路径
return { path: '/target', query: { from: to.path } }
}
}
]
编程式导航
在组件方法中使用this.$router进行控制跳转:
// 基础跳转
this.$router.push('/target-path')
// 带参数跳转
this.$router.push({ path: '/user', query: { id: 123 } })
// 替换当前历史记录
this.$router.replace('/login')
// 路由名称跳转(需提前定义name)
this.$router.push({ name: 'userProfile' })
导航守卫控制
通过路由守卫实现条件重定向,在router/index.js中添加全局守卫:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
组件内守卫
在组件内部使用beforeRouteEnter等守卫:
export default {
beforeRouteEnter(to, from, next) {
if (!localStorage.getItem('token')) {
next({ path: '/login' })
} else {
next()
}
}
}
服务端重定向(SSR场景)
在Nuxt.js或SSR项目中,服务端重定向示例:
// Nuxt中间件
export default function({ redirect }) {
if (process.server) {
redirect(302, '/maintenance')
}
}
动态路径重定向
处理带参数的重定向场景:
{
path: '/user/:id',
redirect: to => `/profile/${to.params.id}`
}
注意:重定向时需考虑路由历史记录模式(hash/history),确保服务器配置正确。对于复杂逻辑,建议结合Vuex状态管理进行权限判断。







