Nuxt.js中使用$auth登录后如何避免跳转首页停留在当前页
解决方案
Nuxt默认的$auth模块会在登录成功后触发默认重定向到首页,是因为模块内置的redirect规则优先级高于你写的路由跳转逻辑,按以下步骤调整即可:
步骤1:修改nuxt.config.js中的auth配置
关闭登录成功后默认跳转到首页的全局规则:
// nuxt.config.js export default { // 其他原有配置保留 auth: { redirect: { login: '/login', // 未登录时访问权限页的跳转地址,按需保留 logout: '/', // 退出登录后的跳转地址,按需保留 callback: false, // 第三方登录回调才需要用到,此处可设为false home: false // 核心配置:关闭登录成功后自动跳首页的默认规则 }, // 你原有laravelJWT的相关配置不需要改动,直接保留即可 strategies: { laravelJWT: { // 你的原有provider配置 } } } }
步骤2:调整login登录方法
调用loginWith时显式禁用自动跳转,同时替换原有的$router.back()逻辑,避免无历史记录时跳转异常:
async login() { try { this.loading(true) await this.$auth.loginWith('laravelJWT', { data: this.form, redirect: false // 显式禁用本次登录的自动跳转逻辑 }) // 配置不需要留在当前页的路由名称,比如登录页、注册页等,这类页面登录后直接跳首页 const excludeRouteNames = ['login', 'register'] if (this.redirectHome || excludeRouteNames.includes(this.$route.name)) { this.$router.push('/') } else { // 非特定页面场景,刷新当前页即可 window.location.reload() // 如果不需要强制刷新页面,也可以直接调用当前页的状态刷新方法,性能更好 // 示例:this.$store.dispatch('refreshCurrentPageData') } this.$emit('is-logged') } catch (error) { this.loginError = true } finally { this.loading(false) } }
补充说明
之前fake redirect不生效的核心原因是全局的redirect.home配置没有设为false,默认的全局跳转规则优先级更高,会覆盖你写的自定义跳转逻辑。
内容的提问来源于stack exchange,提问作者Bruno Henrique Gaignoux Gomes
相关产品推荐
相关产品推荐

