Files
chart-view/src/router/router-guards.ts
2025-12-23 01:06:06 +08:00

87 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Router } from 'vue-router';
import { PageEnum, PreviewEnum } from '@/enums/pageEnum'
import { useSystemStore } from '@/store/modules/systemStore/systemStore'
import { SystemStoreUserInfoEnum, SystemStoreEnum } from '@/store/modules/systemStore/systemStore.d'
import { useDesignStore } from '@/store/modules/designStore/designStore'
import { ThemeEnum } from '@/enums/styleEnum'
import { setHtmlTheme } from '@/utils'
/**
* 从 URL 参数中提取 token 并自动登录
*/
function autoLoginFromUrlToken(query: any) {
const token = query.token
if (token) {
const systemStore = useSystemStore()
// 存储 token 到 store
systemStore.setItem(SystemStoreEnum.USER_INFO, {
[SystemStoreUserInfoEnum.USER_TOKEN]: token,
[SystemStoreUserInfoEnum.TOKEN_NAME]: 'token',
[SystemStoreUserInfoEnum.USER_ID]: 'iframe-user',
[SystemStoreUserInfoEnum.USER_NAME]: 'iframe-user',
[SystemStoreUserInfoEnum.NICK_NAME]: 'iframe-user',
})
console.log('[GoView] 已从 URL 参数中获取 token 并自动登录')
return true
}
return false
}
/**
* 从 URL 参数中提取 mode 并切换主题
*/
function autoSwitchThemeFromUrlMode(query: any) {
const mode = query.mode
if (mode) {
const designStore = useDesignStore()
const isDark = mode === 'dark'
const themeName = isDark ? ThemeEnum.DARK : ThemeEnum.LIGHT
// 如果主题不同则设置并持久化到localStorage
if (designStore.themeName !== themeName) {
designStore.setTheme(isDark)
setHtmlTheme(themeName)
console.log(`[GoView] 已切换主题为 ${mode} 并存储到本地`)
}
}
}
export function createRouterGuards(router: Router) {
// 前置
router.beforeEach(async (to, from, next) => {
// http://localhost:3000/#/chart/preview/792622755697790976?t=123
// 把外部动态参数放入window.route.params后续API动态接口可以用window.route?.params?.t来拼接参数
// @ts-ignore
if (!window.route) window.route = {params: {}}
// @ts-ignore
Object.assign(window.route.params, to.query)
const Loading = window['$loading'];
Loading && Loading.start();
const isErrorPage = router.getRoutes().findIndex((item) => item.name === to.name);
if (isErrorPage === -1) {
next({ name: PageEnum.ERROR_PAGE_NAME_404 })
return
}
// iframe 嵌入模式:自动从 URL 参数中提取 token 并登录
autoLoginFromUrlToken(to.query)
// iframe 嵌入模式:自动从 URL 参数中提取 mode 并切换主题
autoSwitchThemeFromUrlMode(to.query)
// iframe 嵌入模式:完全跳过登录验证,允许所有路由访问
next()
})
router.afterEach((to, _, failure) => {
const Loading = window['$loading'];
document.title = (to?.meta?.title as string) || document.title;
Loading && Loading.finish();
})
// 错误
router.onError((error) => {
console.log(error, '路由错误');
});
}