vue-vben-admin/src/router/guard/index.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-09-28 20:19:10 +08:00
import type { Router } from 'vue-router';
import { Modal, notification } from 'ant-design-vue';
2020-10-30 21:32:05 +08:00
2020-09-28 20:19:10 +08:00
import { createProgressGuard } from './progressGuard';
import { createPermissionGuard } from './permissionGuard';
import { createPageLoadingGuard } from './pageLoadingGuard';
2020-10-30 21:32:05 +08:00
2020-11-23 00:35:15 +08:00
import { useGlobSetting, useProjectSetting } from '/@/settings/use';
2020-10-30 21:32:05 +08:00
2020-10-14 21:08:07 +08:00
import { getIsOpenTab, setCurrentTo } from '/@/utils/helper/routeHelper';
2020-10-27 22:48:08 +08:00
import { setTitle } from '/@/utils/browser';
2020-10-30 21:32:05 +08:00
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel';
2020-09-28 20:19:10 +08:00
2020-11-10 21:58:19 +08:00
import { tabStore } from '/@/store/modules/tab';
2020-11-23 00:35:15 +08:00
const globSetting = useGlobSetting();
2020-09-28 20:19:10 +08:00
export function createGuard(router: Router) {
2020-11-23 00:35:15 +08:00
const { openNProgress, closeMessageOnSwitch, removeAllHttpPending } = useProjectSetting();
let axiosCanceler: AxiosCanceler | null;
if (removeAllHttpPending) {
axiosCanceler = new AxiosCanceler();
}
2020-11-12 23:58:44 +08:00
createPageLoadingGuard(router);
router.beforeEach(async (to) => {
2020-11-10 21:58:19 +08:00
// Determine whether the tab has been opened
2020-10-14 21:08:07 +08:00
const isOpen = getIsOpenTab(to.fullPath);
to.meta.inTab = isOpen;
2020-11-10 21:58:19 +08:00
// Notify routing changes
const { fullPath, path, query, params, name, meta } = to;
tabStore.commitLastChangeRouteState({
fullPath,
path,
query,
params,
name,
meta,
} as any);
2020-09-28 20:19:10 +08:00
try {
if (closeMessageOnSwitch) {
Modal.destroyAll();
notification.destroy();
}
2020-09-28 20:19:10 +08:00
// TODO Some special interfaces require long connections
// Switching the route will delete the previous request
removeAllHttpPending && axiosCanceler!.removeAllPending();
2020-09-28 20:19:10 +08:00
} catch (error) {
console.warn('basic guard error:' + error);
}
2020-10-14 21:08:07 +08:00
setCurrentTo(to);
return true;
2020-09-28 20:19:10 +08:00
});
2020-10-27 22:48:08 +08:00
router.afterEach((to) => {
// change html title
2020-10-30 21:32:05 +08:00
setTitle(to.meta.title, globSetting.title);
2020-10-27 22:48:08 +08:00
});
openNProgress && createProgressGuard(router);
2020-09-28 20:19:10 +08:00
createPermissionGuard(router);
}