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

70 lines
1.7 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 { getToken } from '@/utils';
import { RouteNameMap } from './routes';
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
});
}
function handleRouterAction(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
const token = getToken();
const isLogin = Boolean(token);
const needLogin = Boolean(to.meta?.requiresAuth);
const routerAction: [boolean, () => void][] = [
// 已登录状态跳转登录页,跳转至首页
[
isLogin && to.name === RouteNameMap.get('login'),
() => {
next({ name: RouteNameMap.get('root') });
}
],
// 不需要登录权限的页面直接通行
[
!needLogin,
() => {
next();
}
],
// 未登录状态进入需要登录权限的页面
[
!isLogin && needLogin,
() => {
const redirectUrl = window.location.href;
next({ name: RouteNameMap.get('login'), query: { redirectUrl } });
}
],
// 登录状态进入需要登录权限的页面,直接通行
[
needLogin && isLogin,
() => {
next();
}
]
];
routerAction.some(item => {
const flag = item[0];
if (flag) {
item[1]();
}
return flag;
});
}