mirror of
https://github.com/m-xlsea/ruoyi-plus-soybean.git
synced 2025-09-24 07:49:47 +08:00
refactor(projects): 优化路由声明,添加路由模块导入,规范路相关文件夹
This commit is contained in:
27
src/router/guard/index.ts
Normal file
27
src/router/guard/index.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import type { Router } from 'vue-router';
|
||||
import { useTitle } from '@vueuse/core';
|
||||
import { useAppStore } from '@/store';
|
||||
import { handlePagePermission } from './permission';
|
||||
|
||||
/**
|
||||
* 路由守卫函数
|
||||
* @param router - 路由实例
|
||||
*/
|
||||
export function createRouterGuide(router: Router) {
|
||||
const { resetScrollBehavior } = useAppStore();
|
||||
|
||||
router.beforeEach((to, from, next) => {
|
||||
// 开始 loadingBar
|
||||
window.$loadingBar?.start();
|
||||
// 页面跳转逻辑
|
||||
handlePagePermission(to, from, next);
|
||||
});
|
||||
router.afterEach(to => {
|
||||
// 设置document title
|
||||
useTitle(to.meta.title as string);
|
||||
// 结束 loadingBar
|
||||
window.$loadingBar?.finish();
|
||||
// 重置滚动条行为
|
||||
resetScrollBehavior();
|
||||
});
|
||||
}
|
56
src/router/guard/permission.ts
Normal file
56
src/router/guard/permission.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
|
||||
import { router, routeName } from '@/router';
|
||||
import { getToken, getLoginRedirectUrl } from '@/utils';
|
||||
|
||||
type RouterAction = [boolean, () => void];
|
||||
|
||||
/** 处理页面的权限 */
|
||||
export function handlePagePermission(
|
||||
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(router);
|
||||
next({ name: routeName('login'), query: { redirectUrl } });
|
||||
}
|
||||
],
|
||||
// 登录状态进入需要登录权限的页面,直接通行
|
||||
[
|
||||
isLogin && needLogin,
|
||||
() => {
|
||||
next();
|
||||
}
|
||||
]
|
||||
];
|
||||
|
||||
routerAction.some(item => {
|
||||
const [flag, callback] = item;
|
||||
if (flag) {
|
||||
callback();
|
||||
}
|
||||
return flag;
|
||||
});
|
||||
}
|
Reference in New Issue
Block a user