im 管理后台
This commit is contained in:
@@ -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: 'ErrorPage',
|
||||
component: Layout,
|
||||
meta: {
|
||||
title: 'ErrorPage',
|
||||
hideBreadcrumb: true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/:path(.*)*',
|
||||
name: 'ErrorPageSon',
|
||||
component: ErrorPage,
|
||||
meta: {
|
||||
title: 'ErrorPage',
|
||||
hideBreadcrumb: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const RedirectRoute: AppRouteRecordRaw = {
|
||||
path: '/redirect',
|
||||
name: RedirectName,
|
||||
component: Layout,
|
||||
meta: {
|
||||
title: RedirectName,
|
||||
hideBreadcrumb: true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '/redirect/:path(.*)',
|
||||
name: `${RedirectName}Son`,
|
||||
component: () => import('@/views/redirect/index.vue'),
|
||||
meta: {
|
||||
title: RedirectName,
|
||||
hideBreadcrumb: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
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');
|
||||
@@ -0,0 +1,151 @@
|
||||
import { adminMenus } from '@/api/system/menu';
|
||||
import { constantRouterIcon } from './router-icons';
|
||||
import { RouteRecordRaw } from 'vue-router';
|
||||
import { Layout, ParentLayout } from '@/router/constant';
|
||||
import type { AppRouteRecordRaw } from '@/router/types';
|
||||
|
||||
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, parent?): any[] => {
|
||||
return routerMap.map((item) => {
|
||||
const currentRouter: any = {
|
||||
// 路由地址 动态拼接生成如 /dashboard/workplace
|
||||
path: `${(parent && parent.path) || ''}/${item.path}`,
|
||||
// 路由名称,建议唯一
|
||||
name: item.name || '',
|
||||
// 该路由对应页面的 组件
|
||||
component: item.component,
|
||||
// meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
|
||||
meta: {
|
||||
...item.meta,
|
||||
label: item.meta.title,
|
||||
icon: constantRouterIcon[item.meta.icon] || null,
|
||||
permissions: item.meta.permissions || null,
|
||||
},
|
||||
};
|
||||
|
||||
// 为了防止出现后端返回结果不规范,处理有可能出现拼接出两个 反斜杠
|
||||
currentRouter.path = currentRouter.path.replace('//', '/');
|
||||
// 重定向 ,菜单类型为目录默认默认跳转
|
||||
if(item.meta.type === 1){
|
||||
item.redirect && (currentRouter.redirect = item.redirect);
|
||||
}
|
||||
// 是否有子菜单,并递归处理
|
||||
if (item.children && item.children.length > 0) {
|
||||
//如果未定义 redirect 默认第一个子路由为 redirect
|
||||
if(item.meta.type === 1) {
|
||||
!item.redirect && (currentRouter.redirect = `${item.path}/${item.children[0].path}`);
|
||||
}
|
||||
// Recursion
|
||||
currentRouter.children = routerGenerator(item.children, currentRouter);
|
||||
}
|
||||
|
||||
return currentRouter;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态生成菜单
|
||||
*/
|
||||
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
adminMenus()
|
||||
.then((result) => {
|
||||
const routeList = routerGenerator(result.list);
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 移除隐藏的菜单
|
||||
* @param menus
|
||||
*/
|
||||
export const removeHiddenMenus = (menus: any[]) => {
|
||||
const arr: any[] = [];
|
||||
for (let j = 0; j < menus.length; j++) {
|
||||
if (menus[j].meta?.type === 3) {
|
||||
continue;
|
||||
}
|
||||
if (menus[j].meta?.hidden === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (menus[j].children?.length > 0) {
|
||||
menus[j].children = removeHiddenMenus(menus[j].children);
|
||||
if (menus[j].children?.length === 0) {
|
||||
delete menus[j].children;
|
||||
}
|
||||
}
|
||||
arr.push(menus[j]);
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import { App } from 'vue';
|
||||
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
|
||||
import { RedirectRoute } from '@/router/base';
|
||||
import { PageEnum } from '@/enums/pageEnum';
|
||||
import { createRouterGuards } from './router-guards';
|
||||
import { createRouterIcon } from './router-icons';
|
||||
|
||||
// @ts-ignore
|
||||
const modules = import.meta.glob('./modules/**/*.ts');
|
||||
const routeModuleList: RouteRecordRaw[] = [];
|
||||
|
||||
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'),
|
||||
meta: {
|
||||
title: '登录',
|
||||
},
|
||||
};
|
||||
|
||||
//需要验证权限
|
||||
export const asyncRoutes = [...routeModuleList];
|
||||
|
||||
//普通路由 无需验证权限
|
||||
export const constantRouter: any[] = [LoginRoute, RootRoute, RedirectRoute];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(''),
|
||||
routes: constantRouter,
|
||||
strict: true,
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
});
|
||||
|
||||
export function setupRouter(app: App) {
|
||||
app.use(router);
|
||||
// 创建路由守卫
|
||||
createRouterGuards(router);
|
||||
createRouterIcon();
|
||||
}
|
||||
|
||||
export default router;
|
||||
@@ -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 } from '@/store/mutation-types';
|
||||
import { storage } from '@/utils/Storage';
|
||||
import { PageEnum } from '@/enums/pageEnum';
|
||||
import { ErrorPageRoute } from '@/router/base';
|
||||
import { jump } from '@/utils/http/axios';
|
||||
import { getNowUrl } from '@/utils/urlUtils';
|
||||
|
||||
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 Loading = window['$loading'] || null;
|
||||
Loading && Loading.start();
|
||||
|
||||
if (from.path === LOGIN_PATH && to.name === 'errorPage') {
|
||||
next(PageEnum.BASE_HOME);
|
||||
return;
|
||||
}
|
||||
|
||||
// Whitelist can be directly entered
|
||||
if (whitePathList.includes(to.path as PageEnum)) {
|
||||
await userStore.LoadLoginConfig();
|
||||
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 redirectPath = (from.query.redirect || to.path) as string;
|
||||
const redirect = decodeURIComponent(redirectPath);
|
||||
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
|
||||
const userInfo = await userStore.GetInfo();
|
||||
await userStore.LoadLoginConfig();
|
||||
|
||||
// 是否允许获取微信openid
|
||||
if (userStore.allowWxOpenId()) {
|
||||
let path = nextData.path;
|
||||
if (path === LOGIN_PATH) {
|
||||
path = PageEnum.BASE_HOME_REDIRECT;
|
||||
}
|
||||
|
||||
const URI = getNowUrl() + '#' + path;
|
||||
jump('/wechat/authorize', { type: 'openId', syncRedirect: URI });
|
||||
return;
|
||||
}
|
||||
|
||||
await userStore.GetConfig();
|
||||
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);
|
||||
}
|
||||
|
||||
asyncRouteStore.setDynamicAddedRoute(true);
|
||||
next(nextData);
|
||||
Loading && Loading.finish();
|
||||
});
|
||||
|
||||
router.afterEach((to, _, failure) => {
|
||||
document.title = (to?.meta?.title as string) || document.title;
|
||||
if (isNavigationFailure(failure)) {
|
||||
//console.log('failed navigation', failure)
|
||||
}
|
||||
const Loading = window['$loading'] || null;
|
||||
Loading && Loading.finish();
|
||||
});
|
||||
|
||||
router.onError((error) => {
|
||||
console.log(error, '路由错误');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { renderIcon } from '@/utils';
|
||||
import * as antdIcons from '@vicons/antd';
|
||||
// import * as x5Icons from '@vicons/ionicons5';
|
||||
|
||||
export const constantRouterIcon = {};
|
||||
|
||||
export function createRouterIcon() {
|
||||
for (const element of Object.keys(antdIcons)) {
|
||||
constantRouterIcon[element] = renderIcon(antdIcons[element]);
|
||||
}
|
||||
|
||||
// for (const element of Object.keys(x5Icons)) {
|
||||
// constantRouterIcon[element] = renderIcon(x5Icons[element]);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { RouteRecordRaw, RouteMeta } from 'vue-router';
|
||||
import { defineComponent } from 'vue';
|
||||
|
||||
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;
|
||||
label: 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;
|
||||
}
|
||||
Reference in New Issue
Block a user