vben
2020-11-10 4baf90a5c87493939830129efaa146624faabbcc
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
import type { Router } from 'vue-router';
 
import { Modal, notification } from 'ant-design-vue';
 
import { createProgressGuard } from './progressGuard';
import { createPermissionGuard } from './permissionGuard';
import { createPageLoadingGuard } from './pageLoadingGuard';
 
import { useSetting } from '/@/hooks/core/useSetting';
 
import { getIsOpenTab, setCurrentTo } from '/@/utils/helper/routeHelper';
import { setTitle } from '/@/utils/browser';
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel';
 
import { tabStore } from '/@/store/modules/tab';
 
const { projectSetting, globSetting } = useSetting();
export function createGuard(router: Router) {
  const { openNProgress, closeMessageOnSwitch, removeAllHttpPending } = projectSetting;
  let axiosCanceler: AxiosCanceler | null;
  if (removeAllHttpPending) {
    axiosCanceler = new AxiosCanceler();
  }
  router.beforeEach(async (to) => {
    // Determine whether the tab has been opened
    const isOpen = getIsOpenTab(to.fullPath);
    to.meta.inTab = isOpen;
 
    // Notify routing changes
    const { fullPath, path, query, params, name, meta } = to;
    tabStore.commitLastChangeRouteState({
      fullPath,
      path,
      query,
      params,
      name,
      meta,
    } as any);
 
    try {
      if (closeMessageOnSwitch) {
        Modal.destroyAll();
        notification.destroy();
      }
      // TODO Some special interfaces require long connections
      // Switching the route will delete the previous request
      removeAllHttpPending && axiosCanceler!.removeAllPending();
    } catch (error) {
      console.warn('basic guard error:' + error);
    }
    setCurrentTo(to);
    return true;
  });
 
  router.afterEach((to) => {
    // change html title
    setTitle(to.meta.title, globSetting.title);
  });
 
  openNProgress && createProgressGuard(router);
  createPermissionGuard(router);
  createPageLoadingGuard(router);
}