refactor(projects): 精简版+动态路由权限初步

This commit is contained in:
Soybean
2022-01-03 22:20:10 +08:00
parent 7a0648dba5
commit de2057f141
354 changed files with 2053 additions and 22117 deletions

View File

@ -1,27 +1,29 @@
import type { Router } from 'vue-router';
import { useTitle } from '@vueuse/core';
import { useAppStore } from '@/store';
import { handlePagePermission } from './permission';
import { useRouteStore } from '@/store';
/**
* 路由守卫函数
* @param router - 路由实例
*/
export function createRouterGuide(router: Router) {
const { resetScrollBehavior } = useAppStore();
const routeStore = useRouteStore();
const { initDynamicRoute } = useRouteStore();
router.beforeEach((to, from, next) => {
router.beforeEach(async (to, from, next) => {
if (!routeStore.isAddedDynamicRoute) {
await initDynamicRoute(router);
next();
return;
}
// 开始 loadingBar
window.$loadingBar?.start();
// 页面跳转逻辑
handlePagePermission(to, from, next);
next();
});
router.afterEach(to => {
// 设置document title
useTitle(to.meta.title as string);
useTitle(to.meta.title);
// 结束 loadingBar
window.$loadingBar?.finish();
// 重置滚动条行为
resetScrollBehavior();
});
}

View File

@ -1,56 +1 @@
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
import { routeName } from '@/router';
import { getToken } 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 redirect = to.fullPath;
next({ name: routeName('login'), query: { redirect } });
}
],
// 登录状态进入需要登录权限的页面,直接通行
[
isLogin && needLogin,
() => {
next();
}
]
];
routerAction.some(item => {
const [flag, callback] = item;
if (flag) {
callback();
}
return flag;
});
}
export default {};