index.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import type { RouteRecordRaw } from 'vue-router';
  2. import type { App } from 'vue';
  3. import { createRouter, createWebHashHistory } 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. // 应该添加到路由的初始路由列表。
  19. routes: basicRoutes as unknown as RouteRecordRaw[],
  20. // 是否应该禁止尾部斜杠。默认为假
  21. strict: true,
  22. scrollBehavior: () => ({ left: 0, top: 0 }),
  23. });
  24. // reset router
  25. export function resetRouter() {
  26. router.getRoutes().forEach((route) => {
  27. const { name } = route;
  28. if (name && !WHITE_NAME_LIST.includes(name as string)) {
  29. router.hasRoute(name) && router.removeRoute(name);
  30. }
  31. });
  32. }
  33. // config router
  34. // 配置路由器
  35. export function setupRouter(app: App<Element>) {
  36. app.use(router);
  37. }