go-view/src/router/router-guards.ts

45 lines
1.3 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 { loginCheck } from '@/utils'
// 路由白名单
const routerAllowList = [
// 登录
PageEnum.BASE_LOGIN_NAME,
// 预览
PreviewEnum.CHART_PREVIEW_NAME
]
export function createRouterGuards(router: Router) {
// 前置
router.beforeEach(async (to, from, next) => {
// http://localhost:3000/#/chart/preview/792622755697790976?t=123
// 把外部动态参数放入sessionStorage后续API动态接口可以用sessionStorage拼接参数
for (let queryKey in to.query) {
window.sessionStorage.setItem(queryKey,<string>to.query[queryKey])
}
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 })
}
// @ts-ignore
if (!routerAllowList.includes(to.name) && !loginCheck()) {
next({ name: PageEnum.BASE_LOGIN_NAME })
}
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, '路由错误');
});
}