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

Vue.js实现登录后重定向至原访问页面的技术问询

实现登录后返回原访问页面的方案

一、修改路由守卫(router/index.js)

找到路由守卫中的未登录跳转登录页逻辑,替换为以下代码,把用户原本要访问的页面路径作为参数传递给登录页:

// 替换原有的这段代码
if (!store.state.authStore.token) {
  window.location.href.includes("/login")
    ? next()
    : (window.location.href = process.env.VUE_APP_LANDING_URL + "/login");
}

// 修改为:
if (!store.state.authStore.token) {
  // 排除登录页本身
  if (to.name !== 'login') {
    // 保存原页面的完整路径作为redirect参数
    const redirectUrl = encodeURIComponent(to.fullPath);
    window.location.href = `${process.env.VUE_APP_LANDING_URL}/login?redirect=${redirectUrl}`;
  } else {
    next();
  }
}

同时修改requiresAuth分支的catch块跳转逻辑,同样带上原页面路径:

.catch(() => {
  // 原代码:window.location.href = process.env.VUE_APP_LANDING_URL;
  // 修改为:
  const redirectUrl = encodeURIComponent(to.fullPath);
  window.location.href = `${process.env.VUE_APP_LANDING_URL}/login?redirect=${redirectUrl}`;
});

二、修改登录组件(Login.vue)

找到登录成功后的跳转逻辑,修改handleLogin和login方法中的跳转代码,从URL参数中获取原页面路径并跳转:

1. 修改handleLogin方法

// 原代码:this.$router.push("/");
// 修改为:
const redirect = this.$route.query.redirect || "/";
this.$router.push(decodeURIComponent(redirect));

2. 修改login方法

// 原代码:this.$router.push("/");
// 修改为:
const redirect = this.$route.query.redirect || "/";
this.$router.push(decodeURIComponent(redirect));

逻辑说明

  1. 用户访问需要认证的页面(如profile)时,路由守卫检测到未登录,将当前页面的完整路径编码后作为redirect参数拼接到登录页URL,跳转至登录页。
  2. 用户完成登录后,登录组件读取URL中的redirect参数,解码后跳转到该路径;如果没有redirect参数(比如直接访问登录页),则默认跳转到首页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:00:50