tdesign-vue-next-starter/src/router/index.ts
悠静萝莉 f9f9e91438
feat: 将现有代码迁移至TS严格模式 - 禁止any类型 (#519)
* feat: 新增type enum类型

* feat: 开启禁止any类型规则

* types: 优化通知标签类型

* types: 补充标签页移除方法类型

* types: 补充请求工具类型

* types: 补充store相关类型

* types: 补充路由相关类型

* types: 补充钩子类型

* types: 补充页面组件类型

* types: 补充布局类型

* fix: 修复编译问题
2023-05-24 10:40:06 +08:00

86 lines
2.4 KiB
TypeScript

import uniq from 'lodash/uniq';
import { createRouter, createWebHistory, RouteRecordRaw, useRoute } from 'vue-router';
const env = import.meta.env.MODE || 'development';
// 导入homepage相关固定路由
const homepageModules = import.meta.glob('./modules/**/homepage.ts', { eager: true });
// 导入modules非homepage相关固定路由
const fixedModules = import.meta.glob('./modules/**/!(homepage).ts', { eager: true });
// 其他固定路由
const defaultRouterList: Array<RouteRecordRaw> = [
{
path: '/login',
name: 'login',
component: () => import('@/pages/login/index.vue'),
},
{
path: '/',
redirect: '/dashboard/base',
},
];
// 存放固定路由
export const homepageRouterList: Array<RouteRecordRaw> = mapModuleRouterList(homepageModules);
export const fixedRouterList: Array<RouteRecordRaw> = mapModuleRouterList(fixedModules);
export const allRoutes = [...homepageRouterList, ...fixedRouterList, ...defaultRouterList];
// 固定路由模块转换为路由
export function mapModuleRouterList(modules: Record<string, unknown>): Array<RouteRecordRaw> {
const routerList: Array<RouteRecordRaw> = [];
Object.keys(modules).forEach((key) => {
// @ts-ignore
const mod = modules[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
routerList.push(...modList);
});
return routerList;
}
export const getRoutesExpanded = () => {
const expandedRoutes: Array<string> = [];
fixedRouterList.forEach((item) => {
if (item.meta && item.meta.expanded) {
expandedRoutes.push(item.path);
}
if (item.children && item.children.length > 0) {
item.children
.filter((child) => child.meta && child.meta.expanded)
.forEach((child: RouteRecordRaw) => {
expandedRoutes.push(item.path);
expandedRoutes.push(`${item.path}/${child.path}`);
});
}
});
return uniq(expandedRoutes);
};
export const getActive = (maxLevel = 3): string => {
const route = useRoute();
if (!route.path) {
return '';
}
return route.path
.split('/')
.filter((_item: string, index: number) => index <= maxLevel && index > 0)
.map((item: string) => `/${item}`)
.join('');
};
const router = createRouter({
history: createWebHistory(env === 'site' ? '/starter/vue-next/' : import.meta.env.VITE_BASE_URL),
routes: allRoutes,
scrollBehavior() {
return {
el: '#app',
top: 0,
behavior: 'smooth',
};
},
});
export default router;