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

Vue项目认证登录后跳转首页失效问题求助

问题解决:Vue登录后无法跳转首页的原因及修复

核心问题1:认证状态未全局共享

你在Login组件里定义的isAuthenticated是组件局部的ref,路由文件里直接从Login组件导入的isAuthenticated是全新的独立实例,和组件内的状态完全不关联。所以登录后组件内的状态变为true,但路由里的状态还是初始的false,导致beforeEnter守卫仍然拦截跳转,把你打回登录页。

核心问题2:路由守卫逻辑错误

Home路由的beforeEnter里,else分支的router.push('/')完全多余,会触发无限路由跳转循环——进入Home路由时又执行push,再次触发守卫,陷入死循环。


修复步骤

1. 创建全局认证状态文件

新建src/utils/auth.ts,把认证状态抽成全局可共享的ref:

import { ref } from 'vue'
export const isAuthenticated = ref(false)

2. 修改Login组件,使用全局状态

替换组件内的局部ref,改用全局的认证状态:

<template>
  <!-- 模板部分保持不变 -->
</template>
<script setup lang="ts">
import { ref } from 'vue'
import router from '@/router/index'
// 导入全局认证状态,删除局部的isAuthenticated定义
import { isAuthenticated } from '@/utils/auth'

const accessToken = ref('');

const checkAccessToken = () => {
  if (accessToken.value === '123') {
    isAuthenticated.value = true;
    console.log(isAuthenticated.value);
    console.log('Authenticated');
    router.push('/');
  }
};
</script>

3. 修复路由文件的逻辑

  • 替换导入的isAuthenticated为全局版本
  • 删除beforeEnter里多余的router.push('/')
  • (可选)改用全局路由守卫,统一处理所有需要认证的路由

修改后的路由代码:

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '@/views/LoginView.vue'
import AboutView from '../views/AboutView.vue';
// 导入全局认证状态
import { isAuthenticated } from '@/utils/auth'; 

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: LoginView
    },
    {
      path: '/',
      name: 'Home',
      meta: {
        requiresAuth: true
      },
      component: AboutView,
      beforeEnter:(to,_,next)=>{
        if(to.meta.requiresAuth && !isAuthenticated.value){
          next('/login');
        } else {
          // 仅调用next()即可,删除冗余的router.push('/')
          next();
        }
      }
    }
  ]
})

// 可选:改用全局路由守卫,替代单个路由的beforeEnter,更适合多路由场景
// router.beforeEach((to, from, next) => {
//   if (to.meta.requiresAuth && !isAuthenticated.value) {
//     next('/login');
//   } else {
//     next();
//   }
// })

export default router

额外建议

  • 生产环境不要用硬编码的token('123'),建议结合后端接口做真实认证
  • 可以把认证状态持久化到localStorage,避免页面刷新后状态丢失:
    // auth.ts里修改初始化逻辑
    export const isAuthenticated = ref(!!localStorage.getItem('isAuthenticated'))
    
    // 登录时同步到localStorage
    isAuthenticated.value = true;
    localStorage.setItem('isAuthenticated', 'true')
    
    // 登出时清除
    isAuthenticated.value = false;
    localStorage.removeItem('isAuthenticated')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:56:11