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

Vue项目未登录、会话过期时跳转登录页的路由配置问题

解决方案

核心修改点

  • 给需要鉴权的页面(如Dashboard)添加meta鉴权标识,新增/login公开路由
  • 调整全局路由守卫逻辑,未登录状态下访问所有非公开路由直接跳转登录页,已登录状态下访问登录页自动跳转仪表盘
  • 新增Axios响应拦截器处理后端返回的会话过期(401状态码)场景

修改后的完整路由代码

import Vue from 'vue'
import Router from 'vue-router'

// Containers
const TheContainer = () => import('@/containers/TheContainer')
// Views
const Dashboard = () => import('@/views/Dashboard')
// 导入登录页组件(请替换为你实际的登录页路径)
const Login = () => import('@/views/Login')

Vue.use(Router)

let router = new Router({
  mode: 'hash',
  linkActiveClass: 'active',
  scrollBehavior: () => ({ y: 0 }),
  routes: configRoutes()
})

router.beforeEach((to, from, next) => {
  let roles = localStorage.getItem("roles");
  if(roles != null){
    roles = roles.split(',')
  }
  const isLogin = roles !== null && roles.length > 0

  // 已登录状态访问登录页,直接跳转到仪表盘
  if (to.path === '/login' && isLogin) {
    return next('/dashboard')
  }

  if(to.matched.some(record => record.meta.requiresAdmin)) {
    if(roles != null && roles.indexOf('admin') >= 0 ){
      next()
    }else{
      next({
        path: '/login',
        params: { nextUrl: to.fullPath }
      })
    }
  }else if(to.matched.some(record => record.meta.requiresUser)) {
    if(roles != null && roles.indexOf('user') >= 0 ){
      next()
    }else{
      next({
        path: '/login',
        params: { nextUrl: to.fullPath }
      })
    }
  }else{
    next()
  }
})

export default router

function configRoutes () { 
  return [
    // 新增公开登录路由
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      component: TheContainer,
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: Dashboard,
          // 新增鉴权标识,根据你的权限需求调整为requiresAdmin或requiresUser
          meta: { requiresAdmin: true }
        },
        // 其他需要登录访问的子路由,均需添加对应的meta鉴权标识
      ]
    },
  ]
}

会话过期全局处理

路由守卫只能判断本地存储的登录状态是否存在,后端侧会话过期需要通过接口响应拦截处理,在你封装Axios的文件中添加如下代码即可:

import router from './router' // 导入上述路由实例

axios.interceptors.response.use(
  response => response,
  error => {
    // 后端返回401代表会话失效/未授权
    if (error.response && error.response.status === 401) {
      // 清空本地存储的登录信息
      localStorage.removeItem('roles')
      // 跳转登录页
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:15:03