Files
2026-09-29 15:52:07 +08:00

84 lines
2.9 KiB
TypeScript

import { createRouter, createWebHashHistory } from 'vue-router';
import { ApiError, onUnauthorized } from './api';
import { clearSession, loadMe, session } from './session';
// hash 路由:刷新任何页面都落在 /m/ 这一个入口上,后台不用为前端路由做重写。
export const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/login',
name: 'login',
component: () => import('./views/LoginView.vue'),
meta: { public: true },
},
{
path: '/',
component: () => import('./views/ShellView.vue'),
children: [
{ path: '', redirect: { name: 'desktops' } },
{ path: 'desktops', name: 'desktops', component: () => import('./views/DevicesView.vue') },
{
path: 'conversations',
name: 'conversations',
component: () => import('./views/ConversationsView.vue'),
},
{ path: 'me', name: 'me', component: () => import('./views/MeView.vue') },
],
},
{ path: '/:pathMatch(.*)*', redirect: { name: 'desktops' } },
],
});
router.beforeEach(async (to) => {
if (to.meta.public) return true;
if (!session.token) return { name: 'login', query: { redirect: to.fullPath } };
if (!session.me) {
try {
await loadMe();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
clearSession();
return { name: 'login', query: { redirect: to.fullPath } };
}
// 网络问题:放行,由页面自己展示错误并提供重试。
}
}
return true;
});
onUnauthorized(() => {
clearSession();
const current = router.currentRoute.value;
// 首次导航还没完成(路由守卫里 loadMe 得到 401):由守卫带着目标地址跳登录,
// 这里再跳一次会把 redirect 覆盖成起始的 "/"。
if (!current.matched.length) return;
if (current.name !== 'login') {
void router.replace({ name: 'login', query: { redirect: current.fullPath, expired: '1' } });
}
});
// 发版后,还开着的旧页面按旧文件名去拉页面代码会 404。整页刷新一次就能拿到新版本;
// 10 秒内只刷新一次,服务端真出问题时不会无限刷新。
const CHUNK_RELOAD_KEY = 'wecom-mobile-chunk-reload';
router.onError((error, to) => {
const message = String((error as Error)?.message || error);
const staleChunk =
/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(
message,
);
if (!staleChunk) return;
let last = 0;
try {
last = Number(window.sessionStorage.getItem(CHUNK_RELOAD_KEY) || 0);
window.sessionStorage.setItem(CHUNK_RELOAD_KEY, String(Date.now()));
} catch {
// sessionStorage 不可用时照样刷新一次
}
if (Date.now() - last > 10_000) {
window.location.assign(`${import.meta.env.BASE_URL}#${to.fullPath}`);
window.location.reload();
}
});