某系统动态路由架构解析

4 阅读3分钟

某系统动态路由架构解析

系统概述

某系统采用基于角色权限的动态路由架构,实现了细粒度的权限控制和菜单动态生成。系统通过Vue Router、Pinia状态管理和TypeScript类型系统构建了一套完整的权限管理解决方案。

核心架构设计

1. 路由分层设计

系统采用三层路由架构

// 1. 基础路由(无需权限)
const baseRoutes: RouteRecordRaw[] = [
  { path: '/redirect', component: Layout, meta: { hidden: true } },
  { path: '/login', component: () => import('@/views/login/index.vue') }
]

// 2. 错误页面路由
const errorRoutes: RouteRecordRaw[] = [
  { path: '/:pathMatch(.*)*', component: () => import('@/views/error/404.vue') },
  { path: '/403', component: () => import('@/views/error/403.vue') }
]

// 3. 主页路由(数据看板)
const homeRoute: RouteRecordRaw = {
  path: '/', redirect: '/home',
  children: [{ path: '/home', component: () => import('@/views/home/index.vue') }]
}

2. 动态路由生成机制

路由状态管理 ()
// 核心路由生成函数
const generateRoutes = async (): Promise<RouteRecordRaw[]> => {
  try {
    // 获取用户权限对应的菜单数据
    const menuDataToRole = menuDataToRoleFun(getMenuByThisPermission())
    // 格式化异步路由
    const asyncRoutes = formatAsyncRoutes(menuDataToRole)
    // 合并到全局路由
    setRoutes(asyncRoutes)
    return cloneDeep(asyncRoutes)
  } catch (error) {
    Message.error(`路由生成失败-${error}`)
    return []
  }
}
智能组件加载系统

系统实现了智能组件路径匹配算法,支持多种组件路径格式:

export const loadView = (view: string) => {
  const normalizedView = view.replace(/^\//, '')
  
  // 生成所有可能的匹配模式
  const possiblePatterns = [
    normalizedView,
    `${normalizedView}/index`,
    normalizedView.replace('/index', ''),
    normalizedView.replace('/index', '') + '/index'
  ]
  
  // 自动扫描views目录下所有.vue文件
  const modules = import.meta.glob('@/views/**/*.vue')
  
  for (const path in modules) {
    const relativePath = path
      .replace(/^\/src\/views\//, '')
      .replace(/\.vue$/, '')
    
    if (uniquePatterns.includes(relativePath)) {
      return () => modules[path]()
    }
  }
}

3. 权限守卫系统 ()

路由守卫核心逻辑
router.beforeEach(async (to, _from, next) => {
  const token = getToken()
  const userStore = useUserStore()

  if (token) {
    if (to.path === '/login') {
      // 已登录时访问登录页,重定向到首页
      resetRouteGenerationState()
      next({ path: '/', replace: true })
      return
    }

    // 动态路由生成控制
    if (!isDynamicRoutesGenerated) {
      try {
        const redirectRoute = await handleDynamicRoutes(router, to)
        next(redirectRoute)
      } catch {
        userStore.resetToken()
        resetRouteGenerationState()
        next(`/login?redirect=${to.path}`)
      }
      return
    }

    next()
  } else {
    // 未登录处理逻辑
    resetRouteGenerationState()
    whiteList.includes(to.path) ? next() : next('/login')
  }
})
动态路由加载流程
async function handleDynamicRoutes(router: Router, to: RouteLocationNormalized) {
  const userStore = useUserStore()
  const routeStore = useRouteStore()

  // 1. 获取用户信息和权限
  await userStore.getInfo()

  // 2. 生成可访问的路由表
  const accessRoutes = await routeStore.generateRoutes()

  // 3. 动态添加路由到路由器
  accessRoutes.forEach((route) => {
    if (!isHttp(route.path)) {
      router.addRoute(route)
    }
  })

  // 4. 标记路由已生成并刷新菜单状态
  isDynamicRoutesGenerated = true
  routeStore.$patch({ routes: [...routeStore.routes] })

  return { ...to, replace: true }
}

4. 菜单系统集成

菜单组件 ()

系统实现了响应式菜单系统,支持自动刷新和状态同步:

// 菜单刷新机制
const menuRefreshKey = ref(0)
const forceRefreshMenu = () => {
  menuRefreshKey.value += 1
  console.log('菜单强制刷新触发,刷新键:', menuRefreshKey.value)
}

// 监听路由变化自动刷新菜单
watch(() => routeStore.routes, () => {
  setTimeout(() => forceRefreshMenu(), 100)
}, { deep: true })

关键技术特性

1. 类型安全的路由系统

系统通过TypeScript实现了完整的类型定义:

declare module 'vue-router' {
  interface RouteMeta {
    title?: string           // 路由标题
    svgIcon?: string         // SVG图标
    hidden?: boolean         // 是否隐藏
    keepAlive?: boolean      // 是否缓存
    breadcrumb?: boolean     // 是否显示面包屑
    showInTabs?: boolean    // 是否显示在标签页
    affix?: boolean         // 是否固定标签页
    roles?: string[]        // 访问权限
    sort?: number          // 排序
  }
}

2. 智能路径解析

系统支持多种组件路径格式,解决了常见的路径匹配问题:

  • pumpBusinessManagementpumpBusinessManagement/index.vue
  • pumpBusinessManagement/indexpumpBusinessManagement/index.vue
  • system/usersystem/user/index.vue

3. 权限粒度控制

系统支持细粒度的权限控制:

  • 菜单级权限:控制菜单项的显示/隐藏
  • 路由级权限:控制路由的访问权限
  • 操作级权限:控制页面内具体操作按钮的权限

系统优势

  1. 高性能:基于import.meta.glob的动态导入,实现按需加载
  2. 高可维护性:清晰的模块划分和类型定义
  3. 强扩展性:支持动态添加路由和权限配置
  4. 用户体验优秀:无缝的路由切换和菜单刷新
  5. 安全性高:完整的权限验证和路由守卫

典型应用场景

企业管理模块

// 路由配置示例
{
  path: '/pumpBusinessManagement',
  redirect: '/pumpBusinessManagement/index',
  component: 'Layout',
  meta: { title: '企业管理', icon: 'icon-building' },
  children: [{
    path: 'index',
    component: 'pumpBusinessManagement/index',
    meta: { title: '企业管理', keepAlive: true }
  }]
}

用户中心跳转刷新

系统还实现了从数据看板跳转到用户中心时的自动刷新机制,通过sessionStorage标记实现页面状态重置。

总结

该系统的动态路由架构体现了现代前端权限管理的最佳实践,通过模块化设计、类型安全和智能路径匹配等技术,构建了一个既强大又易维护的权限管理系统。该系统不仅满足了当前业务需求,还为未来的功能扩展提供了良好的基础架构支持。