index.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import {
  2. createRouter,
  3. createWebHashHistory,
  4. type RouteLocationNormalized
  5. } from "vue-router";
  6. import { constantRoutes } from "./routes";
  7. import { useCachedViewStoreHook } from "@/store/modules/cachedView";
  8. import NProgress from "@/utils/progress";
  9. import setPageTitle from "@/utils/set-page-title";
  10. import useUserStore from "@/store/modules/user";
  11. let router = createRouter({
  12. history: createWebHashHistory(),
  13. routes: constantRoutes
  14. });
  15. export interface toRouteType extends RouteLocationNormalized {
  16. meta: {
  17. title?: string;
  18. noCache?: boolean;
  19. };
  20. }
  21. // const whiteList = ['/roleSelect'];
  22. router.beforeEach((to: toRouteType, from, next) => {
  23. NProgress.start();
  24. // 路由缓存
  25. useCachedViewStoreHook().addCachedView(to);
  26. // 页面 title
  27. setPageTitle(to.meta.title);
  28. const role = localStorage.getItem('role');
  29. const roles = useUserStore().roles;
  30. if(to.path === '/' || (!!role && roles.includes(role))) {
  31. next();
  32. } else if (!!role) {
  33. useUserStore().setRoles(role);
  34. next({ path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name as string }); // hack方法 确保addRoutes已完成
  35. } else {
  36. next({ path: '/' });
  37. }
  38. });
  39. router.afterEach(() => {
  40. NProgress.done();
  41. });
  42. export default router;