签入版本

This commit is contained in:
2026-09-12 11:46:38 +08:00
commit c5a9d20cb8
932 changed files with 116861 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
import type { AppRouteRecordRaw } from '@/router/types';
import { ErrorPage, RedirectName, Layout } from '@/router/constant';
// 404 on a page
export const ErrorPageRoute: AppRouteRecordRaw = {
path: '/:path(.*)*',
name: 'ErrorPageParent',
component: Layout,
meta: {
title: 'ErrorPage',
hideBreadcrumb: true,
},
children: [
{
path: '/:path(.*)*',
name: 'ErrorPage',
component: ErrorPage,
meta: {
title: 'ErrorPage',
hideBreadcrumb: true,
},
},
],
};
export const RedirectRoute: AppRouteRecordRaw = {
path: '/redirect',
name: `${RedirectName}Parent`,
component: Layout,
meta: {
title: RedirectName,
hideBreadcrumb: true,
},
children: [
{
path: '/redirect/:path(.*)',
name: RedirectName,
component: () => import('@/views/redirect/index.vue'),
meta: {
title: RedirectName,
hideBreadcrumb: true,
},
},
],
};
+7
View File
@@ -0,0 +1,7 @@
export const RedirectName = 'Redirect';
export const ErrorPage = () => import('@/views/exception/404.vue');
export const Layout = () => import('@/layout/index.vue');
export const ParentLayout = () => import('@/layout/parentLayout.vue');
+176
View File
@@ -0,0 +1,176 @@
import { adminMenus } from '@/api/common/menu';
import { constantRouterIcon } from './router-icons';
import { RouteRecordRaw } from 'vue-router';
import { Layout, ParentLayout } from '@/router/constant';
import type { AppRouteRecordRaw } from '@/router/types';
import { ProfileOutlined } from '@ant-design/icons-vue';
import { renderIcon } from '@/utils/index';
const Iframe = () => import('@/views/iframe/index.vue');
const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>();
LayoutMap.set('LAYOUT', Layout);
LayoutMap.set('IFRAME', Iframe);
/**
* 格式化 后端 结构信息并递归生成层级路由表
* @param routerMap
* @param parent
* @returns {*}
*/
export const routerGenerator = (routerMap): any[] => {
return routerMap.map((item) => {
const names = /http(s)?:/.test(item.component) ? item.component : item.path.replaceAll('/', '');
item.meta = {
title: item.parentId == 0 && item.children.length == 0 ? '' : item.name,
icon: constantRouterIcon[item.icon2] || null,
sort: item.sort,
permissions: item.permission,
hidden: item.hide ? true : false,
isRoot: item.parentId == 0 && item.children.length == 0 ? true : false,
alwaysShow: item.parentId == 0 && item.children.length == 0 ? true : false,
frameSrc: item.target == 1 ? item.component : '',
target: item.target == 2 ? true : false,
};
let components = '';
if (item.parentId == 0 && (item.children.length == 0 || item.children.length > 0)) {
components = 'LAYOUT';
} else if (item.target == 0) {
components = item.component;
} else if (item.target == 1) {
components = 'IFRAME';
}
const currentRouter: any = {
path: item.target == 2 ? '' : item.path,
// 路由名称,建议唯一
name: names,
// 该路由对应页面的 组件
component: components,
// meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
meta: {
...item.meta,
permissions: item.meta.permissions || null,
},
};
// 为了防止出现后端返回结果不规范,处理有可能出现拼接出两个 反斜杠
// currentRouter.path = currentRouter.path.replace('//', '/');
// 重定向
item.redirect && (currentRouter.redirect = item.redirect);
// 是否有子菜单,并递归处理
if (item.children && item.children.length > 0) {
//如果未定义 redirect 默认第一个子路由为 redirect
!item.redirect && (currentRouter.redirect = `${item.children[0].path}`);
// Recursion
currentRouter.children = routerGenerator(item.children, currentRouter);
} else {
if (item.parentId == 0 && item.children.length == 0) {
currentRouter.children = [];
if (item.target == 1 && /http(s)?:/.test(item.component)) {
currentRouter.children.push({
path: item.path,
name: names,
meta: {
title: item.name,
frameSrc: item.component,
icon: constantRouterIcon[item.icon2],
hidden: item.hide ? true : false,
},
component: 'IFRAME',
});
} else {
currentRouter.children.push({
path: item.path,
name: names,
meta: {
title: item.name,
icon: constantRouterIcon[item.icon2],
activeMenu: names,
target: item.target == 2 ? true : false,
hidden: item.hide ? true : false,
},
component: item.component,
});
}
}
}
return currentRouter;
});
};
/**
* 动态生成菜单
* @returns {Promise<Router>}
*/
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
return new Promise((resolve, reject) => {
adminMenus()
.then((result) => {
const routeList = routerGenerator(result);
asyncImportRoute(routeList);
resolve(routeList);
})
.catch((err) => {
reject(err);
});
});
};
/**
* 查找views中对应的组件文件
* */
let viewsModules: Record<string, () => Promise<Recordable>>;
export const asyncImportRoute = (routes: AppRouteRecordRaw[] | undefined): void => {
viewsModules = viewsModules || import.meta.glob('../views/**/*.{vue,tsx}');
if (!routes) return;
routes.forEach((item) => {
if (!item.component && item.meta?.frameSrc) {
item.component = 'IFRAME';
}
const { component, name } = item;
const { children } = item;
if (component) {
const layoutFound = LayoutMap.get(component as string);
if (layoutFound) {
item.component = layoutFound;
} else {
item.component = dynamicImport(viewsModules, component as string);
}
} else if (name) {
item.component = ParentLayout;
}
children && asyncImportRoute(children);
});
};
/**
* 动态导入
* */
export const dynamicImport = (
viewsModules: Record<string, () => Promise<Recordable>>,
component: string,
) => {
const keys = Object.keys(viewsModules);
const matchKeys = keys.filter((key) => {
let k = key.replace('../views', '');
const lastIndex = k.lastIndexOf('.');
k = k.substring(0, lastIndex);
return k === component;
});
if (matchKeys?.length === 1) {
const matchKey = matchKeys[0];
return viewsModules[matchKey];
}
if (matchKeys?.length > 1) {
console.warn(
'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure',
);
return;
}
};
/**
* 查找第一个路由
* */
export const findFirstRoutePath = (routes) => {
return routes.length > 0 ? (routes[0].redirect ? routes[0].redirect : routes[0].path) : '';
};
+75
View File
@@ -0,0 +1,75 @@
import type { AppRouteModule, AppRouteRecordRaw } from '@/router/types';
import type { Router, RouteRecordNormalized } from 'vue-router';
import { cloneDeep, omit } from 'lodash-es';
import { createRouter, createWebHashHistory } from 'vue-router';
// Routing level upgrade
function promoteRouteLevel(routeModule: AppRouteModule) {
// Use vue-router to splice menus
let router: Router | null = createRouter({
routes: [routeModule as unknown as RouteRecordNormalized],
history: createWebHashHistory(),
});
const routes = router.getRoutes();
addToChildren(routes, routeModule.children || [], routeModule);
router = null;
routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
}
// Add all sub-routes to the secondary route
function addToChildren(
routes: RouteRecordNormalized[],
children: AppRouteRecordRaw[],
routeModule: AppRouteModule,
) {
for (let index = 0; index < children.length; index++) {
const child = children[index];
const route = routes.find((item) => item.name === child.name);
if (!route) {
continue;
}
routeModule.children = routeModule.children || [];
if (!routeModule.children.find((item) => item.name === route.name)) {
routeModule.children?.push(route as unknown as AppRouteModule);
}
if (child.children?.length) {
addToChildren(routes, child.children, routeModule);
}
}
}
/**
* Convert multi-level routing to level 2 routing
*/
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
const modules: AppRouteModule[] = cloneDeep(routeModules);
for (let index = 0; index < modules.length; index++) {
const routeModule = modules[index];
if (!isMultipleRoute(routeModule)) {
continue;
}
promoteRouteLevel(routeModule);
}
return modules;
}
// Determine whether the level exceeds 2 levels
function isMultipleRoute(routeModule: AppRouteModule) {
if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
return false;
}
const children = routeModule.children;
let flag = false;
for (let index = 0; index < children.length; index++) {
const child = children[index];
if (child.children?.length) {
flag = true;
break;
}
}
return flag;
}
+73
View File
@@ -0,0 +1,73 @@
import { App } from 'vue';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { RedirectRoute } from '@/router/base';
import { PageEnum } from '@/enums/pageEnum';
import { createRouterGuards } from './router-guards';
const modules: any = import.meta.glob('./modules/**/*.ts', { eager: true });
const routeModuleList: RouteRecordRaw[] = [];
const modulesVue = import.meta.glob('/src/views/**/*.vue');
export function getModulesKey() {
return Object.keys(modulesVue).map((item) => item.replace('/src/views', '').replace('.vue', ''));
}
Object.keys(modules).forEach((key) => {
const mod = modules[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
routeModuleList.push(...modList);
});
function sortRoute(a, b) {
return (a.meta?.sort || 0) - (b.meta?.sort || 0);
}
routeModuleList.sort(sortRoute);
export const RootRoute: RouteRecordRaw = {
path: '/',
name: 'Root',
redirect: PageEnum.BASE_HOME,
meta: {
title: 'Root',
},
};
export const LoginRoute: RouteRecordRaw = {
path: '/login',
name: 'Login',
component: () => import('@/views/login/index.vue'),
// component: () => import('@/views/login/newLogin.vue'),
meta: {
title: '登录 - Django+AntDesign前后端分离版本',
},
};
//需要验证权限
export const asyncRoutes = [...routeModuleList];
//普通路由 无需验证权限
export const constantRouter: any[] = [LoginRoute, RootRoute, RedirectRoute];
export const router = createRouter({
history: createWebHistory(''),
routes: constantRouter,
strict: true,
scrollBehavior(to) {
if (to.hash) {
return {
el: to.hash,
behavior: 'smooth',
};
}
},
});
export function setupRouter(app: App) {
app.use(router);
// 创建路由守卫
createRouterGuards(router);
}
export default router;
+8
View File
@@ -0,0 +1,8 @@
import { generatorMenu } from '@/utils/index';
import { useAsyncRouteStore } from '@/store/modules/asyncRoute';
import { Menu } from '../types';
export const getMenus = async (): Promise<Menu[]> => {
const asyncRouteStore = useAsyncRouteStore();
return generatorMenu(asyncRouteStore.getMenus);
};
+112
View File
@@ -0,0 +1,112 @@
import type { RouteRecordRaw } from 'vue-router';
import { isNavigationFailure, Router } from 'vue-router';
import { useUserStoreWidthOut } from '@/store/modules/user';
import { useAsyncRouteStoreWidthOut } from '@/store/modules/asyncRoute';
import { ACCESS_TOKEN,FIRST_ROUTE } from '@/store/mutation-types';
import { storage } from '@/utils/Storage';
import { PageEnum } from '@/enums/pageEnum';
import { ErrorPageRoute } from '@/router/base';
import { findFirstRoutePath } from '@/router/generator-routers';
import {findTreeByPath} from "@/utils/auth";
const LOGIN_PATH = PageEnum.BASE_LOGIN;
const whitePathList = [LOGIN_PATH]; // no redirect whitelist
export function createRouterGuards(router: Router) {
const userStore = useUserStoreWidthOut();
const asyncRouteStore = useAsyncRouteStoreWidthOut();
router.beforeEach(async (to, from, next) => {
const $loadingBar = window['$loadingBar'];
$loadingBar && $loadingBar.start();
// Whitelist can be directly entered
if (whitePathList.includes(to.path as PageEnum)) {
next();
return;
}
const token = storage.get(ACCESS_TOKEN);
if (!token) {
// You can access without permissions. You need to set the routing meta.ignoreAuth to true
if (to.meta.ignoreAuth) {
next();
return;
}
// redirect login page
const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
path: LOGIN_PATH,
replace: true,
};
if (to.path) {
redirectData.query = {
...redirectData.query,
redirect: to.path,
};
}
next(redirectData);
return;
}
if (asyncRouteStore.getIsDynamicAddedRoute) {
next();
return;
}
const userInfo = await userStore.GetInfo();
const routes = await asyncRouteStore.generateRoutes(userInfo);
// 动态添加可访问路由表
routes.forEach((item) => {
router.addRoute(item as unknown as RouteRecordRaw);
});
//添加404
const isErrorPage = router.getRoutes().findIndex((item) => item.name === ErrorPageRoute.name);
if (isErrorPage === -1) {
router.addRoute(ErrorPageRoute as unknown as RouteRecordRaw);
}
const firstRoutePath = findFirstRoutePath(routes)
storage.set(FIRST_ROUTE,firstRoutePath)
if (from.path === LOGIN_PATH && (to.name === 'errorPage' || !to.name)) {
next(firstRoutePath);
return;
}
let formPath = findTreeByPath(routes,from.query.redirect).length > 0 ? from.query.redirect:to.path
const redirectPath = (formPath) as string;
const redirect = decodeURIComponent(redirectPath);
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
asyncRouteStore.setDynamicAddedRoute(true);
next(nextData);
$loadingBar && $loadingBar.finish();
});
router.afterEach((to, _, failure) => {
const $loadingBar = window['$loadingBar'];
document.title =
(to?.meta?.documentTitle ? to?.meta?.documentTitle : (to?.meta?.title as string)) ||
document.title;
if (isNavigationFailure(failure)) {
//console.log('failed navigation', failure)
}
const asyncRouteStore = useAsyncRouteStoreWidthOut();
// 在这里设置需要缓存的组件名称
const keepAliveComponents = asyncRouteStore.keepAliveComponents;
const currentComName: any = to.matched.find((item) => item.name == to.name)?.name;
if (currentComName && !keepAliveComponents.includes(currentComName) && to.meta?.keepAlive) {
// 需要缓存的组件
keepAliveComponents.push(currentComName);
} else if (!to.meta?.keepAlive || to.name == 'Redirect') {
// 不需要缓存的组件
const index = asyncRouteStore.keepAliveComponents.findIndex((name) => name == currentComName);
if (index != -1) {
keepAliveComponents.splice(index, 1);
}
}
asyncRouteStore.setKeepAliveComponents(keepAliveComponents);
$loadingBar && $loadingBar.finish();
});
}
+10
View File
@@ -0,0 +1,10 @@
import { renderIcon } from '@/utils/index';
import * as AllIcons from '@ant-design/icons-vue';
const icons = Object.keys(AllIcons);
//前端路由图标映射表
const constantRouterIcon = {};
icons.forEach(icon => {
constantRouterIcon[icon] = renderIcon(AllIcons[icon]);
});
export { constantRouterIcon };
+58
View File
@@ -0,0 +1,58 @@
import type { RouteRecordRaw, RouteMeta } from 'vue-router';
import { defineComponent } from 'vue';
export type AppRouteModule = AppRouteRecordRaw;
export type Component<T extends any = any> =
| ReturnType<typeof defineComponent>
| (() => Promise<typeof import('*.vue')>)
| (() => Promise<T>);
// @ts-ignore
export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
name: string;
meta: RouteMeta;
component?: Component | string;
components?: Component;
children?: AppRouteRecordRaw[];
props?: Recordable;
fullPath?: string;
}
export interface Meta {
// 名称
title: string;
// 是否忽略权限
ignoreAuth?: boolean;
//权限数组集合
permissions?: string[];
// 是否不缓存 预留功能 并未生效
noKeepAlive?: boolean;
// 是否固定在tab上
affix?: boolean;
// tab上的图标
icon?: string;
// 跳转地址
frameSrc?: string;
// 外链跳转地址
externalLink?: string;
//隐藏
hidden?: boolean;
}
export interface Menu {
title: string;
key: string;
meta: RouteMeta;
name: string;
component?: Component | string;
components?: Component;
children?: AppRouteRecordRaw[];
props?: Recordable;
fullPath?: string;
icon?: any;
path: string;
permissions?: string[];
redirect?: string;
sort?: number;
}