You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router 登录认证成功后如何自动重定向到用户初始访问路由

实现方案

步骤1:调整路由守卫,携带原始访问路径

修改你的beforeEach全局守卫逻辑,在未认证用户访问需要权限的路由时,将用户原本要访问的完整路径作为redirect查询参数传递到登录页:

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated
  // 仅拦截需要认证的路由
  if (to.matched.some(route => route.meta.requiresAuth) && !isAuthenticated) {
    next({
      name: "Login",
      // 携带原始访问路径作为跳转参数
      query: { redirect: to.fullPath }
    })
    return
  }
  next()
})

步骤2:标记需要登录权限的路由

取消你代码中Collections路由的meta注释,所有需要登录才能访问的路由都加上这个标记即可:

{
  path: "/collections",
  name: "Collections",
  component: Collections,
  meta: { requiresAuth: true }
},

步骤3:登录成功后读取参数完成重定向

在登录页的登录成功逻辑中,优先读取路由参数里的redirect值作为跳转目标,没有该参数时默认跳转到首页:

// 登录接口调用成功后的逻辑
async function handleLogin() {
  // 你的登录请求、存储登录态逻辑
  await store.dispatch("login", loginFormData)
  // 读取跳转参数,做基础安全校验避免开放重定向风险
  const redirect = router.currentRoute.query.redirect
  const targetPath = typeof redirect === "string" && redirect.startsWith("/") ? redirect : "/"
  router.push(targetPath)
}

补充安全提示:增加路径开头校验是为了避免攻击者拼接外部恶意链接作为redirect参数,导致用户登录后跳转到钓鱼站点。

内容的提问来源于stack exchange,提问作者user16780074

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:06:02