2024-05-19 21:20:42 +08:00
|
|
|
|
import type { RouteRecordName, RouteRecordRaw } from 'vue-router';
|
|
|
|
|
|
2024-07-28 14:29:05 +08:00
|
|
|
|
import {
|
|
|
|
|
createRouter,
|
|
|
|
|
createWebHashHistory,
|
|
|
|
|
createWebHistory,
|
|
|
|
|
} from 'vue-router';
|
2024-05-19 21:20:42 +08:00
|
|
|
|
|
2024-06-08 19:49:06 +08:00
|
|
|
|
import { traverseTreeValues } from '@vben/utils';
|
|
|
|
|
|
2024-06-02 15:04:37 +08:00
|
|
|
|
import { createRouterGuard } from './guard';
|
2024-06-02 21:33:31 +08:00
|
|
|
|
import { routes } from './routes';
|
2024-05-19 21:20:42 +08:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @zh_CN 创建vue-router实例
|
|
|
|
|
*/
|
|
|
|
|
const router = createRouter({
|
2024-07-28 14:29:05 +08:00
|
|
|
|
history:
|
|
|
|
|
import.meta.env.VITE_ROUTER_HISTORY === 'hash'
|
|
|
|
|
? createWebHashHistory(import.meta.env.VITE_BASE)
|
|
|
|
|
: createWebHistory(import.meta.env.VITE_BASE),
|
2024-05-19 21:20:42 +08:00
|
|
|
|
// 应该添加到路由的初始路由列表。
|
2024-06-02 21:33:31 +08:00
|
|
|
|
routes,
|
2024-06-08 20:14:04 +08:00
|
|
|
|
scrollBehavior: () => ({ left: 0, top: 0 }),
|
2024-07-28 14:29:05 +08:00
|
|
|
|
// 是否应该禁止尾部斜杠。
|
2024-06-08 20:14:04 +08:00
|
|
|
|
// strict: true,
|
2024-05-19 21:20:42 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @zh_CN 重置所有路由,如有指定白名单除外
|
|
|
|
|
*/
|
|
|
|
|
function resetRoutes() {
|
|
|
|
|
// 获取静态路由所有节点包含子节点的 name,并排除不存在 name 字段的路由
|
|
|
|
|
const staticRouteNames = traverseTreeValues<
|
|
|
|
|
RouteRecordRaw,
|
|
|
|
|
RouteRecordName | undefined
|
2024-06-02 21:33:31 +08:00
|
|
|
|
>(routes, (route) => {
|
2024-05-19 21:20:42 +08:00
|
|
|
|
// 这些路由需要指定 name,防止在路由重置时,不能删除没有指定 name 的路由
|
2024-06-02 21:33:31 +08:00
|
|
|
|
if (import.meta.env.DEV && !route.name) {
|
2024-05-19 21:20:42 +08:00
|
|
|
|
console.warn(
|
2024-06-02 22:13:15 +08:00
|
|
|
|
`The route with the path ${route.path} needs to have the field name specified.`,
|
2024-05-19 21:20:42 +08:00
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
return route.name;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const { getRoutes, hasRoute, removeRoute } = router;
|
2024-06-02 21:33:31 +08:00
|
|
|
|
const allRoutes = getRoutes();
|
|
|
|
|
allRoutes.forEach(({ name }) => {
|
2024-05-19 21:20:42 +08:00
|
|
|
|
// 存在于路由表且非白名单才需要删除
|
|
|
|
|
if (name && !staticRouteNames.includes(name) && hasRoute(name)) {
|
|
|
|
|
removeRoute(name);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
// 创建路由守卫
|
2024-06-02 15:04:37 +08:00
|
|
|
|
createRouterGuard(router);
|
2024-05-19 21:20:42 +08:00
|
|
|
|
|
|
|
|
|
export { resetRoutes, router };
|