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));
逻辑说明
- 用户访问需要认证的页面(如profile)时,路由守卫检测到未登录,将当前页面的完整路径编码后作为
redirect参数拼接到登录页URL,跳转至登录页。 - 用户完成登录后,登录组件读取URL中的
redirect参数,解码后跳转到该路径;如果没有redirect参数(比如直接访问登录页),则默认跳转到首页。
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

