index.ts
7.06 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores';
import { getToken } from '@/utils/auth';
/**
* 路由配置
* 支持多级路由嵌套,配合菜单系统实现多级导航
*/
const routes: RouteRecordRaw[] = [
// ==================== 登录页面 ====================
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue'),
meta: {
title: '登录',
requiresAuth: false, // 不需要认证
},
},
// ==================== 主应用布局 ====================
{
path: '/',
name: 'Layout',
component: () => import('@/layouts/BasicLayout.vue'),
redirect: '/home',
meta: {
requiresAuth: true, // 需要认证
},
children: [
// ==================== 首页模块 ====================
{
path: '/home',
name: 'Home',
component: () => import('@/views/Home.vue'),
redirect: '/home/dashboard',
meta: {
title: '首页',
level: 1,
requiresAuth: true,
},
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/Home.vue'),
meta: {
title: '工作台',
level: 2,
requiresAuth: true,
},
},
{
path: 'analytics',
name: 'Analytics',
component: () => import('@/views/Home.vue'),
meta: {
title: '数据概览',
level: 2,
requiresAuth: true,
},
},
],
},
// ==================== Vue 微应用模块 ====================
{
path: '/subapp-vue/:pathMatch(.*)*',
name: 'SubAppVue',
component: () => import('@/views/MicroApp.vue'),
meta: {
title: '汽车销售智能体',
level: 1,
isMicroApp: true,
requiresAuth: true,
},
},
// ==================== React 微应用模块 ====================
{
path: '/subapp-react/:pathMatch(.*)*',
name: 'SubAppReact',
component: () => import('@/views/MicroApp.vue'),
meta: {
title: 'React 微应用',
level: 1,
isMicroApp: true,
requiresAuth: true,
},
},
],
},
// ==================== 404 页面 ====================
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
meta: {
title: '页面不存在',
requiresAuth: false,
},
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// 白名单:不需要登录的路由
const whiteList = new Set(['/forgot-password', '/login', '/register']);
/**
* 全局前置守卫
*/
router.beforeEach(async (to, _from, next) => {
// 设置页面标题
document.title = to.meta.title
? `${to.meta.title} - SCRM 微前端`
: 'SCRM 微前端平台';
// 获取 token
const token = getToken();
const userStore = useUserStore();
// 判断是否需要认证
const requiresAuth = to.meta.requiresAuth !== false;
if (token) {
// 已登录
if (to.path === '/login') {
// 如果已登录,访问登录页则跳转到首页
next({ path: '/home' });
} else {
// 检查是否已获取用户信息
if (userStore.userInfo) {
// 检查权限
if (to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore);
if (hasPermission) {
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} else {
// 无权限,跳转到 403 或首页
console.warn('无权限访问:', to.path);
next({ path: '/home' });
}
} else {
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
}
} else {
try {
// 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo();
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} catch (error) {
// 获取用户信息失败,清除 token 并跳转到登录页
console.error('获取用户信息失败:', error);
await userStore.logout();
next({
path: '/login',
query: { redirect: to.fullPath },
});
}
}
}
} else {
// 未登录
if (whiteList.has(to.path)) {
// 在白名单中,直接放行
next();
} else if (requiresAuth) {
// 需要认证但未登录,跳转到登录页
next({
path: '/login',
query: { redirect: to.fullPath },
});
} else {
// 不需要认证的页面,直接放行
next();
}
}
});
/**
* 全局后置守卫
*/
router.afterEach((to, from) => {
// 路由跳转完成后的处理
console.log(`[路由] 从 ${from.path} 跳转到 ${to.path}`);
});
/**
* 同步数据到 qiankun 全局状态
* 确保在加载微应用前,主应用的关键数据已经同步到全局状态
*/
async function syncDataToQiankun(userStore: any): Promise<void> {
try {
console.log('[路由守卫] 准备进入微应用,同步数据到 qiankun 全局状态');
// 同步用户信息
if (userStore.userInfo) {
userStore.syncUserToQiankun();
}
// 延迟导入 qiankun 通信模块
const { communicationManager } = await import('@/qiankun/communication');
// 获取当前全局状态,确认数据已同步
const globalState = communicationManager.getGlobalState();
console.log('[路由守卫] 当前全局状态:', globalState);
// 如果用户信息还未同步,强制同步一次
if (!globalState.user && userStore.userInfo) {
console.log('[路由守卫] 检测到用户信息未同步,强制同步');
communicationManager.updateUser({
id: userStore.userInfo.id,
name: userStore.userInfo.name,
avatar: userStore.userInfo.avatar || '👨💼',
role: userStore.roles[0] || 'user',
permissions: userStore.permissions,
});
}
} catch (error) {
console.error('[路由守卫] 同步数据到 qiankun 失败:', error);
}
}
/**
* 检查权限
*/
function checkPermission(route: any, userStore: any): boolean {
// 检查角色
if (route.meta.roles) {
const roles = route.meta.roles as string[];
if (!userStore.hasRole(roles)) {
return false;
}
}
// 检查权限
if (route.meta.permissions) {
const permissions = route.meta.permissions as string[];
if (!userStore.hasPermission(permissions)) {
return false;
}
}
return true;
}
export default router;