Blame view

src/router/guard/index.ts 1.93 KB
vben authored
1
import { RouteLocationNormalized, Router } from 'vue-router';
陈文彬 authored
2
3

import { Modal, notification } from 'ant-design-vue';
vben authored
4
陈文彬 authored
5
6
7
import { createProgressGuard } from './progressGuard';
import { createPermissionGuard } from './permissionGuard';
import { createPageLoadingGuard } from './pageLoadingGuard';
vben authored
8
vben authored
9
import { useGlobSetting, useProjectSetting } from '/@/hooks/setting';
vben authored
10
vben authored
11
import { setTitle } from '/@/utils/browser';
vben authored
12
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel';
陈文彬 authored
13
vben authored
14
import { useI18n } from '/@/hooks/web/useI18n';
vben authored
15
import { REDIRECT_NAME } from '/@/router/constant';
vben authored
16
import { setLastChangeTab } from '/@/logics/mitt/tabChange';
17
18
const { closeMessageOnSwitch, removeAllHttpPending } = useProjectSetting();
vben authored
19
const globSetting = useGlobSetting();
vben authored
20
21
22
23
24
25
26
const body = document.body;

const isHash = (href: string) => {
  return /^#/.test(href);
};
陈文彬 authored
27
export function createGuard(router: Router) {
vben authored
28
  let axiosCanceler: Nullable<AxiosCanceler>;
29
30
31
  if (removeAllHttpPending) {
    axiosCanceler = new AxiosCanceler();
  }
vben authored
32
  const loadedPageMap = new Map<string, boolean>();
vben authored
33
34
  router.beforeEach(async (to) => {
vben authored
35
    to.meta.loaded = !!loadedPageMap.get(to.path);
36
    // Notify routing changes
vben authored
37
    setLastChangeTab(to);
陈文彬 authored
38
    try {
39
40
41
42
      if (closeMessageOnSwitch) {
        Modal.destroyAll();
        notification.destroy();
      }
陈文彬 authored
43
      // Switching the route will delete the previous request
44
      removeAllHttpPending && axiosCanceler!.removeAllPending();
陈文彬 authored
45
46
47
    } catch (error) {
      console.warn('basic guard error:' + error);
    }
vben authored
48
    return true;
陈文彬 authored
49
  });
vben authored
50
vben authored
51
  router.afterEach((to) => {
52
53
54
    // scroll top
    isHash((to as RouteLocationNormalized & { href: string })?.href) && body.scrollTo(0, 0);
vben authored
55
    loadedPageMap.set(to.path, true);
56
vben authored
57
    const { t } = useI18n();
58
vben authored
59
    // change html title
vben authored
60
    to.name !== REDIRECT_NAME && setTitle(t(to.meta.title), globSetting.title);
vben authored
61
  });
vben authored
62
  createPageLoadingGuard(router);
vben authored
63
  createProgressGuard(router);
陈文彬 authored
64
65
  createPermissionGuard(router);
}