Fixes bug 动态路由配置重构

This commit is contained in:
xiaoma
2021-08-10 17:16:58 +08:00
parent 737f967aab
commit 9c512002d2
23 changed files with 179 additions and 98 deletions

View File

@@ -1,6 +1,6 @@
// @ts-ignore
import { NButton } from 'naive-ui';
import { RoleEnum } from '@/enums/roleEnum';
import { PermissionsEnum } from '@/enums/permissionsEnum';
// @ts-ignore
export interface ActionItem extends NButton.props {
onClick?: Fn;
@@ -11,7 +11,7 @@ export interface ActionItem extends NButton.props {
disabled?: boolean;
divider?: boolean;
// 权限编码控制是否显示
auth?: RoleEnum | RoleEnum[] | string | string[];
auth?: PermissionsEnum | PermissionsEnum[] | string | string[];
// 业务控制是否显示
ifShow?: boolean | ((action: ActionItem) => boolean);
}

View File

@@ -7,8 +7,8 @@ export function usePermission() {
* 检查权限
* @param accesses
*/
function _someRoles(accesses: string[]) {
return userStore.getRoles.some((item) => {
function _somePermissions(accesses: string[]) {
return userStore.getPermissions.some((item) => {
const { value }: any = item;
return accesses.includes(value);
});
@@ -20,7 +20,7 @@ export function usePermission() {
* */
function hasPermission(accesses: string[]): boolean {
if (!accesses || !accesses.length) return true;
return _someRoles(accesses);
return _somePermissions(accesses);
}
/**
@@ -28,9 +28,9 @@ export function usePermission() {
* @param accesses
*/
function hasEveryPermission(accesses: string[]): boolean {
const rolesList = userStore.getRoles;
const permissionsList = userStore.getPermissions;
if (Array.isArray(accesses)) {
return accesses.every((access) => !!rolesList[access]);
return accesses.every((access) => !!permissionsList[access]);
}
throw new Error(`[hasEveryPermission]: ${accesses} should be a array !`);
}
@@ -41,9 +41,9 @@ export function usePermission() {
* @param accessMap
*/
function hasSomePermission(accesses: string[]): boolean {
const rolesList = userStore.getRoles;
const permissionsList = userStore.getPermissions;
if (Array.isArray(accesses)) {
return accesses.some((access) => !!rolesList[access]);
return accesses.some((access) => !!permissionsList[access]);
}
throw new Error(`[hasSomePermission]: ${accesses} should be a array !`);
}

View File

@@ -13,7 +13,7 @@ export const ErrorPageRoute: AppRouteRecordRaw = {
children: [
{
path: '/:path(.*)*',
name: 'ErrorPage',
name: 'ErrorPageSon',
component: ErrorPage,
meta: {
title: 'ErrorPage',

View File

@@ -1,16 +0,0 @@
import { renderIcon } from '@/utils/index';
import { DashboardOutlined } from '@vicons/antd';
// import { RouterTransition } from '@/components/transition'
//前端路由映射表
export const constantRouterComponents = {
Layout: () => import('@/layout/index.vue'), //布局
DashboardConsole: () => import('@/views/dashboard/console/console.vue'), // 主控台
DashboardMonitor: () => import('@/views/dashboard/monitor/monitor.vue'), // 监控页
DashboardWorkplace: () => import('@/views/dashboard/workplace/workplace.vue'), // 工作台
};
//前端路由图标映射表
export const constantRouterIcon = {
DashboardOutlined: renderIcon(DashboardOutlined),
};

View File

@@ -1,12 +1,19 @@
import { adminMenus } from '@/api/system/menu';
import { constantRouterComponents, constantRouterIcon } from './constantRouterComponents';
import { constantRouterIcon } from './router-icons';
import router from '@/router/index';
import { constantRouter } from '@/router/index';
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 {*}
@@ -19,21 +26,24 @@ export const routerGenerator = (routerMap, parent?): any[] => {
// 路由名称,建议唯一
name: item.name || '',
// 该路由对应页面的 组件
component: constantRouterComponents[item.component],
component: item.component,
// meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
meta: {
...item.meta,
label: item.meta.title,
icon: constantRouterIcon[item.meta.icon] || null,
permission: item.meta.permission || null,
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.path}/${item.children[0].path}`);
// Recursion
currentRouter.children = routerGenerator(item.children, currentRouter);
}
@@ -43,7 +53,6 @@ export const routerGenerator = (routerMap, parent?): any[] => {
/**
* 动态生成菜单
* @param token
* @returns {Promise<Router>}
*/
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
@@ -51,7 +60,8 @@ export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
adminMenus()
.then((result) => {
const routeList = routerGenerator(result);
const asyncRoutesList = [...constantRouter, ...routeList];
asyncImportRoute(routeList);
const asyncRoutesList = [...routeList, ...constantRouter];
asyncRoutesList.forEach((item) => {
router.addRoute(item);
});
@@ -62,3 +72,56 @@ export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
});
});
};
/**
* 查找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;
}
};

View File

@@ -1,6 +1,6 @@
import { App } from 'vue';
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { ErrorPageRoute, RedirectRoute } from '@/router/base';
import { RedirectRoute } from '@/router/base';
import { PageEnum } from '@/enums/pageEnum';
import { createRouterGuards } from './router-guards';
@@ -40,7 +40,7 @@ export const LoginRoute: RouteRecordRaw = {
};
//需要验证权限
export const asyncRoutes = [ErrorPageRoute, ...routeModuleList];
export const asyncRoutes = [...routeModuleList];
//普通路由 无需验证权限
export const constantRouter: any[] = [LoginRoute, RootRoute, RedirectRoute];

View File

@@ -24,7 +24,7 @@ const routes: Array<RouteRecordRaw> = [
meta: {
title: 'Dashboard',
icon: renderIcon(DashboardOutlined),
permission: ['dashboard_console', 'dashboard_console', 'dashboard_workplace'],
permissions: ['dashboard_console', 'dashboard_console', 'dashboard_workplace'],
sort: 0,
},
children: [
@@ -33,7 +33,7 @@ const routes: Array<RouteRecordRaw> = [
name: `${routeName}_console`,
meta: {
title: '主控台',
permission: ['dashboard_console'],
permissions: ['dashboard_console'],
},
component: () => import('@/views/dashboard/console/console.vue'),
},
@@ -42,7 +42,7 @@ const routes: Array<RouteRecordRaw> = [
// name: `${ routeName }_monitor`,
// meta: {
// title: '监控页',
// permission: ['dashboard_monitor']
// permissions: ['dashboard_monitor']
// },
// component: () => import('@/views/dashboard/monitor/monitor.vue')
// },
@@ -52,7 +52,7 @@ const routes: Array<RouteRecordRaw> = [
meta: {
title: '工作台',
keepAlive: true,
permission: ['dashboard_workplace'],
permissions: ['dashboard_workplace'],
},
component: () => import('@/views/dashboard/workplace/workplace.vue'),
},

View File

@@ -1,9 +1,11 @@
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';
const LOGIN_PATH = PageEnum.BASE_LOGIN;
@@ -29,7 +31,7 @@ export function createRouterGuards(router: Router) {
const token = storage.get(ACCESS_TOKEN);
if (!token) {
// You can access without permission. You need to set the routing meta.ignoreAuth to true
// You can access without permissions. You need to set the routing meta.ignoreAuth to true
if (to.meta.ignoreAuth) {
next();
return;
@@ -60,9 +62,15 @@ export function createRouterGuards(router: Router) {
// 动态添加可访问路由表
routes.forEach((item) => {
router.addRoute(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 redirectPath = (from.query.redirect || to.path) as string;
const redirect = decodeURIComponent(redirectPath);
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };

View File

@@ -0,0 +1,7 @@
import { renderIcon } from '@/utils/index';
import { DashboardOutlined } from '@vicons/antd';
//前端路由图标映射表
export const constantRouterIcon = {
DashboardOutlined: renderIcon(DashboardOutlined),
};

View File

@@ -1,6 +1,5 @@
import type { RouteRecordRaw, RouteMeta } from 'vue-router';
import { defineComponent } from 'vue';
import { RoleEnum } from '@/enums/roleEnum';
export type Component<T extends any = any> =
| ReturnType<typeof defineComponent>
@@ -23,7 +22,7 @@ export interface Meta {
title: string;
// 是否忽略权限
ignoreAuth?: boolean;
roles?: RoleEnum[];
permissions?: string[];
// 是否不缓存
noKeepAlive?: boolean;
// 是否固定在tab上

View File

@@ -41,7 +41,7 @@ const setting = {
//显示图标
showIcon: false,
},
//菜单权限模式 ROLE 前端固定角色 BACK 动态获取
permissionMode: 'ROLE',
//菜单权限模式 FIXED 前端固定路由 BACK 动态获取
permissionMode: 'FIXED',
};
export default setting;

View File

@@ -88,12 +88,12 @@ export const useAsyncRouteStore = defineStore({
},
async generateRoutes(data) {
let accessedRouters;
const roleList = data.roles || [];
const permissionsList = data.permissions || [];
const routeFilter = (route) => {
const { meta } = route;
const { permission } = meta || {};
if (!permission) return true;
return roleList.some((role) => permission.includes(role.value));
const { permissions } = meta || {};
if (!permissions) return true;
return permissionsList.some((item) => permissions.includes(item.value));
};
const { getPermissionMode } = useProjectSetting();
const permissionMode = unref(getPermissionMode);

View File

@@ -13,7 +13,7 @@ export interface IUserState {
username: string;
welcome: string;
avatar: string;
roles: any[];
permissions: any[];
info: any;
}
@@ -24,7 +24,7 @@ export const useUserStore = defineStore({
username: '',
welcome: '',
avatar: '',
roles: [],
permissions: [],
info: Storage.get(CURRENT_USER, {}),
}),
getters: {
@@ -37,8 +37,8 @@ export const useUserStore = defineStore({
getNickname(): string {
return this.username;
},
getRoles(): [any][] {
return this.roles;
getPermissions(): [any][] {
return this.permissions;
},
getUserInfo(): object {
return this.info;
@@ -51,8 +51,8 @@ export const useUserStore = defineStore({
setAvatar(avatar: string) {
this.avatar = avatar;
},
setRoles(roles) {
this.roles = roles;
setPermissions(permissions) {
this.permissions = permissions;
},
setUserInfo(info) {
this.info = info;
@@ -83,12 +83,12 @@ export const useUserStore = defineStore({
getUserInfo()
.then((res) => {
const result = res;
if (result.roles && result.roles.length) {
const roles = result.roles;
that.setRoles(roles);
if (result.permissions && result.permissions.length) {
const permissionsList = result.permissions;
that.setPermissions(permissionsList);
that.setUserInfo(result);
} else {
reject(new Error('getInfo: roles must be a non-null array !'));
reject(new Error('getInfo: permissionsList must be a non-null array !'));
}
that.setAvatar(result.avatar);
resolve(res);
@@ -101,7 +101,7 @@ export const useUserStore = defineStore({
// 登出
async logout() {
this.setRoles([]);
this.setPermissions([]);
this.setUserInfo('');
storage.remove(ACCESS_TOKEN);
storage.remove(CURRENT_USER);

View File

@@ -1,7 +1,7 @@
<template>
<div class="console">
<!--数据卡片-->
<n-grid cols="1 s:2 m:3 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12" :y-gap="8" :cols="4">
<n-grid cols="1 s:2 m:3 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12" :y-gap="8">
<n-grid-item>
<NCard
title="访问量"
@@ -19,14 +19,14 @@
<div class="text-sn">
日同比
<CountTo :startVal="1" suffix="%" :endVal="visits.rise" />
<n-icon size="12" style="color: #00ff6f">
<n-icon size="12" color="#00ff6f">
<component is="CaretUpOutlined" />
</n-icon>
</div>
<div class="text-sn">
周同比
<CountTo :startVal="1" suffix="%" :endVal="visits.decline" />
<n-icon size="12" style="color: #ffde66">
<n-icon size="12" color="#ffde66">
<component is="CaretDownOutlined" />
</n-icon>
</div>
@@ -91,14 +91,14 @@
<div class="text-sn">
日同比
<CountTo :startVal="1" suffix="%" :endVal="orderLarge.rise" />
<n-icon size="12" style="color: #00ff6f">
<n-icon size="12" color="#00ff6f">
<component is="CaretUpOutlined" />
</n-icon>
</div>
<div class="text-sn">
周同比
<CountTo :startVal="1" suffix="%" :endVal="orderLarge.rise" />
<n-icon size="12" style="color: #ffde66">
<n-icon size="12" color="#ffde66">
<component is="CaretDownOutlined" />
</n-icon>
</div>
@@ -130,14 +130,14 @@
<div class="text-sn">
月同比
<CountTo :startVal="1" suffix="%" :endVal="volume.rise" />
<n-icon size="12" style="color: #00ff6f">
<n-icon size="12" color="#00ff6f">
<component is="CaretUpOutlined" />
</n-icon>
</div>
<div class="text-sn">
月同比
<CountTo :startVal="1" suffix="%" :endVal="volume.decline" />
<n-icon size="12" style="color: #ffde66">
<n-icon size="12" color="#ffde66">
<component is="CaretDownOutlined" />
</n-icon>
</div>
@@ -156,14 +156,14 @@
<!--导航卡片-->
<div class="mt-4">
<n-grid cols="1 s:2 m:3 l:8 xl:8 2xl:8" responsive="screen" :x-gap="16" :y-gap="8" :cols="8">
<n-grid cols="1 s:2 m:3 l:8 xl:8 2xl:8" responsive="screen" :x-gap="16" :y-gap="8">
<n-grid-item v-for="(item, index) in iconList" :key="index">
<NCard content-style="padding-top: 0;" size="small" :bordered="false">
<template #footer>
<div class="cursor-pointer">
<p class="flex justify-center">
<span>
<n-icon :size="item.size" class="flex-1" :style="{ color: `${item.color}` }">
<n-icon :size="item.size" class="flex-1" :color="item.color">
<component :is="item.icon" v-on="item.eventObject || {}" />
</n-icon>
</span>

View File

@@ -29,9 +29,9 @@
<style lang="less" scoped>
.page-container {
width: 100%;
background-color: white;
border-radius: 4px;
padding: 50px 0;
height: 100vh;
.text-center {
h1 {

View File

@@ -29,9 +29,9 @@
<style lang="less" scoped>
.page-container {
width: 100%;
background-color: white;
border-radius: 4px;
padding: 50px 0;
height: 100vh;
.text-center {
h1 {

View File

@@ -29,9 +29,9 @@
<style lang="less" scoped>
.page-container {
width: 100%;
background-color: white;
border-radius: 4px;
padding: 50px 0;
height: 100vh;
.text-center {
h1 {

View File

@@ -13,7 +13,7 @@
ref="actionRef"
:actionColumn="actionColumn"
@update:checked-row-keys="onCheckedRow"
:scroll-x="1010"
:scroll-x="1090"
>
<template #tableTitle>
<n-button type="primary" @click="addTable">