Files
wireguard-dashboard-admin/src/router/utils.ts

305 lines
8.7 KiB
TypeScript
Raw Normal View History

2021-12-14 10:51:07 +08:00
import {
RouterHistory,
RouteRecordRaw,
RouteComponent,
createWebHistory,
createWebHashHistory,
RouteRecordNormalized
} from "vue-router";
import { router } from "./index";
import { loadEnv } from "../../build";
import { useTimeoutFn } from "@vueuse/core";
import { RouteConfigs } from "/@/layout/types";
2022-02-27 13:31:19 +08:00
import { buildHierarchyTree } from "/@/utils/tree";
2021-12-14 10:51:07 +08:00
import { usePermissionStoreHook } from "/@/store/modules/permission";
2022-03-01 10:58:55 +08:00
const Layout = () => import("/@/layout/index.vue");
2022-03-03 23:30:08 +08:00
const IFrame = () => import("/@/layout/frameView.vue");
2021-12-14 10:51:07 +08:00
// https://cn.vitejs.dev/guide/features.html#glob-import
2022-01-05 14:17:06 +08:00
const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
2021-12-14 10:51:07 +08:00
// 动态路由
import { getAsyncRoutes } from "/@/api/routes";
// 按照路由中meta下的rank等级升序来排序路由
2022-01-21 14:03:00 +08:00
function ascending(arr: any[]) {
2022-03-17 19:00:01 +08:00
arr.forEach(v => {
2022-03-17 19:53:19 +08:00
if (v?.meta?.rank === null) v.meta.rank = undefined;
2022-03-17 19:00:01 +08:00
if (v?.meta?.rank === 0) {
if (v.name !== "home" && v.path !== "/") {
console.warn("rank only the home page can be 0");
}
}
});
2021-12-14 10:51:07 +08:00
return arr.sort(
(a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
return a?.meta?.rank - b?.meta?.rank;
}
);
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 过滤meta中showLink为false的路由
2022-01-21 14:03:00 +08:00
function filterTree(data: RouteComponent[]) {
2021-12-14 10:51:07 +08:00
const newTree = data.filter(
2022-02-05 14:45:20 +08:00
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
2021-12-14 10:51:07 +08:00
);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 批量删除缓存路由(keepalive)
2022-01-21 14:03:00 +08:00
function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
2021-12-14 10:51:07 +08:00
delAliveRouteList.forEach(route => {
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: route?.name
});
});
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 通过path获取父级路径
2022-01-21 14:03:00 +08:00
function getParentPaths(path: string, routes: RouteRecordRaw[]) {
2021-12-14 10:51:07 +08:00
// 深度遍历查找
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
for (let i = 0; i < routes.length; i++) {
const item = routes[i];
// 找到path则返回父级path
if (item.path === path) return parents;
// children不存在或为空则不递归
if (!item.children || !item.children.length) continue;
// 往下查找时将当前path入栈
parents.push(item.path);
if (dfs(item.children, path, parents).length) return parents;
// 深度遍历查找未找到时当前path 出栈
parents.pop();
}
// 未找到时返回空数组
return [];
}
return dfs(routes, path, []);
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 查找对应path的路由信息
2022-01-21 14:03:00 +08:00
function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
2021-12-14 10:51:07 +08:00
let res = routes.find((item: { path: string }) => item.path == path);
if (res) {
return res;
} else {
for (let i = 0; i < routes.length; i++) {
if (
routes[i].children instanceof Array &&
routes[i].children.length > 0
) {
res = findRouteByPath(path, routes[i].children);
if (res) {
return res;
}
}
}
return null;
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 重置路由
2022-01-21 14:03:00 +08:00
function resetRouter(): void {
2021-12-14 10:51:07 +08:00
router.getRoutes().forEach(route => {
const { name } = route;
if (name) {
router.hasRoute(name) && router.removeRoute(name);
}
});
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 初始化路由
2022-01-21 14:03:00 +08:00
function initRouter(name: string) {
2021-12-14 10:51:07 +08:00
return new Promise(resolve => {
getAsyncRoutes({ name }).then(({ info }) => {
if (info.length === 0) {
usePermissionStoreHook().changeSetting(info);
} else {
formatFlatteningRoutes(addAsyncRoutes(info)).map(
(v: RouteRecordRaw) => {
// 防止重复添加路由
if (
router.options.routes[0].children.findIndex(
value => value.path === v.path
) !== -1
) {
return;
} else {
// 切记将路由push到routes后还需要使用addRoute这样路由才能正常跳转
router.options.routes[0].children.push(v);
// 最终路由进行升序
ascending(router.options.routes[0].children);
if (!router.hasRoute(v?.name)) router.addRoute(v);
2022-03-03 23:30:08 +08:00
const flattenRouters = router
.getRoutes()
.find(n => n.path === "/");
router.addRoute(flattenRouters);
2021-12-14 10:51:07 +08:00
}
resolve(router);
}
);
usePermissionStoreHook().changeSetting(info);
}
router.addRoute({
path: "/:pathMatch(.*)",
redirect: "/error/404"
});
});
});
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/**
*
* @param routesList
* @returns
*/
2022-01-21 14:03:00 +08:00
function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
2022-02-27 13:31:19 +08:00
let hierarchyList = buildHierarchyTree(routesList);
for (let i = 0; i < hierarchyList.length; i++) {
if (hierarchyList[i].children) {
hierarchyList = hierarchyList
2021-12-14 10:51:07 +08:00
.slice(0, i + 1)
2022-02-27 13:31:19 +08:00
.concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
2021-12-14 10:51:07 +08:00
}
}
2022-02-27 13:31:19 +08:00
return hierarchyList;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/**
* keep-alive
* https://github.com/xiaoxian521/vue-pure-admin/issues/67
* @param routesList
* @returns
*/
2022-01-21 14:03:00 +08:00
function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
2021-12-14 10:51:07 +08:00
const newRoutesList: RouteRecordRaw[] = [];
routesList.forEach((v: RouteRecordRaw) => {
if (v.path === "/") {
newRoutesList.push({
component: v.component,
name: v.name,
path: v.path,
redirect: v.redirect,
meta: v.meta,
children: []
});
} else {
newRoutesList[0].children.push({ ...v });
}
});
return newRoutesList;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 处理缓存路由(添加、删除、刷新)
2022-01-21 14:03:00 +08:00
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
2021-12-14 10:51:07 +08:00
switch (mode) {
case "add":
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
break;
case "delete":
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
break;
default:
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
useTimeoutFn(() => {
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
}, 100);
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 过滤后端传来的动态路由 重新生成规范路由
2022-01-21 14:03:00 +08:00
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
2021-12-14 10:51:07 +08:00
if (!arrRoutes || !arrRoutes.length) return;
2022-01-05 14:17:06 +08:00
const modulesRoutesKeys = Object.keys(modulesRoutes);
2021-12-14 10:51:07 +08:00
arrRoutes.forEach((v: RouteRecordRaw) => {
if (v.redirect) {
v.component = Layout;
2022-03-03 23:30:08 +08:00
} else if (v.meta?.frameSrc) {
v.component = IFrame;
2021-12-14 10:51:07 +08:00
} else {
2022-01-05 14:17:06 +08:00
const index = modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
v.component = modulesRoutes[modulesRoutesKeys[index]];
2021-12-14 10:51:07 +08:00
}
if (v.children) {
addAsyncRoutes(v.children);
}
});
return arrRoutes;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html
2022-01-21 14:03:00 +08:00
function getHistoryMode(): RouterHistory {
2021-12-14 10:51:07 +08:00
const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
const historyMode = routerHistory.split(",");
const leftMode = historyMode[0];
const rightMode = historyMode[1];
// no param
if (historyMode.length === 1) {
if (leftMode === "hash") {
return createWebHashHistory("");
} else if (leftMode === "h5") {
return createWebHistory("");
}
} //has param
else if (historyMode.length === 2) {
if (leftMode === "hash") {
return createWebHashHistory(rightMode);
} else if (leftMode === "h5") {
return createWebHistory(rightMode);
}
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
// 是否有权限
2022-01-21 14:03:00 +08:00
function hasPermissions(value: Array<string>): boolean {
2021-12-14 10:51:07 +08:00
if (value && value instanceof Array && value.length > 0) {
const roles = usePermissionStoreHook().buttonAuth;
const permissionRoles = value;
const hasPermission = roles.some(role => {
return permissionRoles.includes(role);
});
if (!hasPermission) {
return false;
}
return true;
} else {
return false;
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
export {
ascending,
filterTree,
initRouter,
resetRouter,
hasPermissions,
getHistoryMode,
addAsyncRoutes,
delAliveRoutes,
getParentPaths,
findRouteByPath,
handleAliveRoute,
formatTwoStageRoutes,
formatFlatteningRoutes
};