refactor: ♻️ 重构API为静态方法实现模块化管理,并将types.ts重命名为model.ts用于存放接口模型定义

This commit is contained in:
hxr
2024-05-04 12:53:08 +08:00
parent a211053176
commit 088bc5e48f
37 changed files with 875 additions and 831 deletions

View File

@@ -1,7 +1,8 @@
import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { listRoutes } from "@/api/menu";
import MenuAPI from "@/api/menu";
import { RouteVO } from "@/api/menu/model";
const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");
@@ -29,25 +30,22 @@ const hasPermission = (roles: string[], route: RouteRecordRaw) => {
};
/**
* 递归过滤有权限的异步(动态)路由
* 递归过滤有权限的动态路由
*
* @param routes 接口返回的异步(动态)路由
* @param routes 接口返回所有的动态路由
* @param roles 用户角色集合
* @returns 返回用户有权限的异步(动态)路由
* @returns 返回用户有权限的动态路由
*/
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
const filterAsyncRoutes = (routes: RouteVO[], roles: string[]) => {
const asyncRoutes: RouteRecordRaw[] = [];
routes.forEach((route) => {
const tmpRoute = { ...route }; // ES6扩展运算符复制新对象
if (!route.name) {
tmpRoute.name = route.path;
}
// 判断用户(角色)是否有该路由的访问权限
const tmpRoute = { ...route } as RouteRecordRaw; // 深拷贝 route 对象 避免污染
if (hasPermission(roles, tmpRoute)) {
// 如果是顶级目录,替换为 Layout 组件
if (tmpRoute.component?.toString() == "Layout") {
tmpRoute.component = Layout;
} else {
// 如果是子目录,动态加载组件
const component = modules[`../../views/${tmpRoute.component}.vue`];
if (component) {
tmpRoute.component = component;
@@ -57,7 +55,7 @@ const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
}
if (tmpRoute.children) {
tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
tmpRoute.children = filterAsyncRoutes(route.children, roles);
}
asyncRoutes.push(tmpRoute);
@@ -66,7 +64,6 @@ const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
return asyncRoutes;
};
// setup
export const usePermissionStore = defineStore("permission", () => {
// state
@@ -76,6 +73,7 @@ export const usePermissionStore = defineStore("permission", () => {
function setRoutes(newRoutes: RouteRecordRaw[]) {
routes.value = constantRoutes.concat(newRoutes);
}
/**
* 生成动态路由
*
@@ -85,10 +83,10 @@ export const usePermissionStore = defineStore("permission", () => {
function generateRoutes(roles: string[]) {
return new Promise<RouteRecordRaw[]>((resolve, reject) => {
// 接口获取所有路由
listRoutes()
.then(({ data: asyncRoutes }) => {
// 根据角色获取有访问权限的路由
const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
MenuAPI.getRoutes()
.then((data) => {
// 过滤有权限的动态路由
const accessedRoutes = filterAsyncRoutes(data, roles);
setRoutes(accessedRoutes);
resolve(accessedRoutes);
})
@@ -97,6 +95,7 @@ export const usePermissionStore = defineStore("permission", () => {
});
});
}
/**
* 获取与激活的顶部菜单项相关的混合模式左侧菜单集合
*/