wanshenmean
10 小时以前 f288ccc545f8cc32bc922c96dfb3cab9a1f92ec6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * 路由配置
 * 支持动态菜单路由注册
 */
import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { useMenuStore } from '@/store/modules/menu';
import { transformMenuToRoutes } from '@/utils/menuTransform';
 
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { anonymous: true },
  },
  {
    path: '/',
    name: 'root',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/home',
    children: [
      { path: '/home', name: 'Home', component: () => import('@/views/dashboard/index.vue'), meta: { title: '首页', icon: 'el-icon-home' } },
    ],
  },
  { path: '/:pathMatch(.*)*', redirect: '/home' },
];
 
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
 
/**
 * 动态注册路由
 */
export async function registerDynamicRoutes() {
  const menuStore = useMenuStore();
 
  if (!menuStore.loaded) {
    await menuStore.loadMenus();
  }
 
  const dynamicRoutes = transformMenuToRoutes(menuStore.menus);
  const rootRoute = router.getRoutes().find((r) => r.name === 'root');
  if (!rootRoute) return;
 
  dynamicRoutes.forEach((route) => {
    const exists = router.getRoutes().some((r) => r.name === route.name);
    if (!exists && route.name) {
      router.addRoute('root', route);
    }
  });
 
  return dynamicRoutes;
}
 
router.beforeEach(async (to, from, next) => {
  if (to.meta?.anonymous) {
    return next();
  }
 
  const userStr = localStorage.getItem('user');
  if (!userStr) {
    return next('/login');
  }
 
  const menuStore = useMenuStore();
  if (!menuStore.loaded) {
    try {
      await registerDynamicRoutes();
    } catch (error) {
      console.error('注册动态路由失败:', error);
    }
  }
 
  next();
});
 
export { router };
export default router;