tdesign-vue-next-starter/src/router/index.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

import { useRoute, createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import uniq from 'lodash/uniq';
const env = import.meta.env.MODE || 'development';
// 自动导入modules文件夹下所有ts文件
const modules = import.meta.globEager('./modules/**/*.ts');
// 路由暂存
const routeModuleList: Array<RouteRecordRaw> = [];
Object.keys(modules).forEach((key) => {
// @ts-ignore
const mod = modules[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
routeModuleList.push(...modList);
});
// 关于单层路由meta 中设置 { single: true } 即可为单层路由,{ hidden: true } 即可在侧边栏隐藏该路由
// 存放动态路由
export const asyncRouterList: Array<RouteRecordRaw> = [...routeModuleList];
// 存放固定的路由
const defaultRouterList: Array<RouteRecordRaw> = [
{
path: '/login',
name: 'login',
component: () => import('@/pages/login/index.vue'),
},
{
path: '/',
redirect: '/dashboard/base',
},
2022-03-07 00:08:57 +08:00
{
path: '/:w+',
name: '404Page',
redirect: '/result/404',
},
];
2022-03-07 00:08:57 +08:00
export const allRoutes = [...defaultRouterList, ...asyncRouterList];
export const getRoutesExpanded = () => {
const expandedRoutes = [];
allRoutes.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 => {
2022-04-28 11:14:13 +08:00
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/' : null),
2022-03-07 00:08:57 +08:00
routes: allRoutes,
scrollBehavior() {
return {
el: '#app',
top: 0,
behavior: 'smooth',
};
},
});
export default router;