ruoyi-plus-soybean/src/router/permission/index.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

import type { Router, RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
2021-09-14 01:31:29 +08:00
import { useTitle } from '@vueuse/core';
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) => {
// 开始 loadingBar
2021-08-18 12:02:59 +08:00
window.$loadingBar?.start();
// 页面跳转逻辑
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
});
}
type RouterAction = [boolean, () => void];
function handleRouterAction(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
const token = getToken();
const isLogin = Boolean(token);
const needLogin = Boolean(to.meta?.requiresAuth);
const routerAction: RouterAction[] = [
// 已登录状态跳转登录页,跳转至首页
[
isLogin && to.name === routeName('login'),
() => {
next({ name: routeName('root') });
}
],
// 不需要登录权限的页面直接通行
[
!needLogin,
() => {
next();
}
],
// 未登录状态进入需要登录权限的页面
[
!isLogin && needLogin,
() => {
const redirectUrl = getLoginRedirectUrl();
next({ name: routeName('login'), query: { redirectUrl } });
}
],
// 登录状态进入需要登录权限的页面,直接通行
[
isLogin && needLogin,
() => {
next();
}
]
];
routerAction.some(item => {
const [flag, callback] = item;
if (flag) {
callback();
}
return flag;
});
}