2021-09-16 13:58:11 +08:00
|
|
|
import type { Router, RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
|
2021-09-14 01:31:29 +08:00
|
|
|
import { useTitle } from '@vueuse/core';
|
2021-11-19 01:33:36 +08:00
|
|
|
import { routeName } from '@/router';
|
|
|
|
|
import { getToken, getLoginRedirectUrl } from '@/utils';
|
2021-08-17 14:59:59 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 路由守卫函数
|
|
|
|
|
* @param router - 路由实例
|
|
|
|
|
*/
|
|
|
|
|
export default function createRouterGuide(router: Router) {
|
|
|
|
|
router.beforeEach((to, from, next) => {
|
2021-09-16 13:58:11 +08:00
|
|
|
// 开始 loadingBar
|
2021-08-18 12:02:59 +08:00
|
|
|
window.$loadingBar?.start();
|
2021-09-16 13:58:11 +08:00
|
|
|
// 页面跳转逻辑
|
|
|
|
|
handleRouterAction(to, from, next);
|
2021-08-17 14:59:59 +08:00
|
|
|
});
|
2021-09-14 01:31:29 +08:00
|
|
|
router.afterEach(to => {
|
|
|
|
|
// 设置document title
|
|
|
|
|
useTitle(to.meta.title as string);
|
|
|
|
|
// 结束 loadingBar
|
2021-08-18 12:02:59 +08:00
|
|
|
window.$loadingBar?.finish();
|
2021-08-17 14:59:59 +08:00
|
|
|
});
|
|
|
|
|
}
|
2021-09-16 13:58:11 +08:00
|
|
|
|
|
|
|
|
function handleRouterAction(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
|
|
|
|
|
const token = getToken();
|
2021-09-16 14:17:57 +08:00
|
|
|
const isLogin = Boolean(token);
|
|
|
|
|
const needLogin = Boolean(to.meta?.requiresAuth);
|
|
|
|
|
|
2021-09-16 13:58:11 +08:00
|
|
|
const routerAction: [boolean, () => void][] = [
|
|
|
|
|
// 已登录状态跳转登录页,跳转至首页
|
|
|
|
|
[
|
2021-11-19 01:33:36 +08:00
|
|
|
isLogin && to.name === routeName('login'),
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
2021-11-19 01:33:36 +08:00
|
|
|
next({ name: routeName('root') });
|
2021-09-16 13:58:11 +08:00
|
|
|
}
|
|
|
|
|
],
|
2021-09-16 14:17:57 +08:00
|
|
|
// 不需要登录权限的页面直接通行
|
2021-09-16 13:58:11 +08:00
|
|
|
[
|
2021-09-16 14:17:57 +08:00
|
|
|
!needLogin,
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
],
|
2021-09-16 14:17:57 +08:00
|
|
|
// 未登录状态进入需要登录权限的页面
|
|
|
|
|
[
|
|
|
|
|
!isLogin && needLogin,
|
|
|
|
|
() => {
|
2021-10-18 18:01:14 +08:00
|
|
|
const redirectUrl = getLoginRedirectUrl();
|
2021-11-19 01:33:36 +08:00
|
|
|
next({ name: routeName('login'), query: { redirectUrl } });
|
2021-09-16 14:17:57 +08:00
|
|
|
}
|
|
|
|
|
],
|
|
|
|
|
// 登录状态进入需要登录权限的页面,直接通行
|
2021-09-16 13:58:11 +08:00
|
|
|
[
|
2021-09-16 18:43:52 +08:00
|
|
|
isLogin && needLogin,
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
2021-09-16 14:17:57 +08:00
|
|
|
next();
|
2021-09-16 13:58:11 +08:00
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
routerAction.some(item => {
|
|
|
|
|
const flag = item[0];
|
|
|
|
|
if (flag) {
|
|
|
|
|
item[1]();
|
|
|
|
|
}
|
|
|
|
|
return flag;
|
|
|
|
|
});
|
|
|
|
|
}
|