index.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { RouteRecordRaw } from 'vue-router';
  2. import type { App } from 'vue';
  3. import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
  4. import { basicRoutes } from './routes';
  5. // 白名单应该包含基本静态路由
  6. const WHITE_NAME_LIST: string[] = [];
  7. const getRouteNames = (array: any[]) =>
  8. array.forEach((item) => {
  9. WHITE_NAME_LIST.push(item.name);
  10. getRouteNames(item.children || []);
  11. });
  12. getRouteNames(basicRoutes);
  13. // app router
  14. // 创建一个可以被 Vue 应用程序使用的路由实例
  15. export const router = createRouter({
  16. // 创建一个 hash 历史记录。
  17. // history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
  18. history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  19. // 应该添加到路由的初始路由列表。
  20. routes: basicRoutes as unknown as RouteRecordRaw[],
  21. // 是否应该禁止尾部斜杠。默认为假
  22. strict: true,
  23. scrollBehavior: () => ({ left: 0, top: 0 }),
  24. });
  25. // reset router
  26. export function resetRouter() {
  27. router.getRoutes().forEach((route) => {
  28. const { name } = route;
  29. if (name && !WHITE_NAME_LIST.includes(name as string)) {
  30. router.hasRoute(name) && router.removeRoute(name);
  31. }
  32. });
  33. }
  34. // config router
  35. // 配置路由器
  36. export function setupRouter(app: App<Element>) {
  37. app.use(router);
  38. }