vue路由实现登录跳转
路由守卫实现登录跳转
在Vue项目中,可以通过路由守卫(Navigation Guards)实现登录跳转逻辑。全局前置守卫router.beforeEach是最常用的方式,在路由跳转前进行拦截和验证。
// router/index.js
import router from './router'
import { getToken } from '@/utils/auth' // 假设有获取token的工具函数
router.beforeEach((to, from, next) => {
const isAuthenticated = getToken() // 检查用户是否已登录
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated) {
next({
path: '/login',
query: { redirect: to.fullPath } // 记录目标路由便于登录后跳转
})
} else {
next()
}
} else {
next()
}
})
路由元信息配置
在路由配置中通过meta字段标记需要认证的路由:

const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '/login',
component: Login
}
]
登录成功后跳转处理
在登录组件中处理登录成功后的跳转逻辑:

// Login.vue
methods: {
handleLogin() {
login(this.loginForm).then(() => {
this.$router.push(this.$route.query.redirect || '/')
})
}
}
动态路由加载
对于权限管理系统,可以结合动态路由实现更精细的控制:
// 登录后动态添加路由
const adminRoutes = [
{ path: '/admin', component: Admin }
]
router.addRoutes(adminRoutes)
组件内守卫
也可以在组件内部使用beforeRouteEnter守卫:
export default {
beforeRouteEnter(to, from, next) {
getToken() ? next() : next('/login')
}
}
以上方法可以根据项目实际需求组合使用,实现完整的登录跳转和权限控制流程。注意处理路由白名单(如登录页、404页等不需要认证的页面),避免死循环跳转。






