permission.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import router, { configRoutes } from "@/router";
  2. import { useUserStore } from "@/store/modules/user";
  3. import { usePermissionStore } from "@/store/modules/permission";
  4. import { useDictionaryStore } from "@/store/modules/dictionary";
  5. import { isNewVersion } from "@/utils/version.js";
  6. import NProgress from "@/utils/nprogress";
  7. import { getUserDicts } from "@/api/auth";
  8. export function setupPermission() {
  9. // 白名单路由
  10. const whiteList = [""];
  11. const userStore = useUserStore();
  12. router.beforeEach(async (to, from, next) => {
  13. NProgress.start();
  14. isNewVersion();
  15. const hasToken = localStorage.getItem("token");
  16. if (hasToken) {
  17. await userStore.getUserInfo();
  18. if (to.path === "/login") {
  19. // 如果已登录,跳转首页
  20. next({ path: "/" });
  21. NProgress.done();
  22. } else {
  23. // 如果已经登录,让菜单加载本地的写死路由的数据
  24. const userStore = usePermissionStore();
  25. if (!userStore.routes || userStore.routes.length === 0) {
  26. userStore.setRoutes(configRoutes);
  27. }
  28. const dictStore = useDictionaryStore();
  29. if (
  30. !dictStore.dicts.value ||
  31. JSON.stringify(dictStore.dicts.value) === "{}"
  32. ) {
  33. const res = await getUserDicts(dictStore.types);
  34. if (res.data) {
  35. dictStore.dicts = res?.data;
  36. }
  37. }
  38. next();
  39. }
  40. } else {
  41. // 未登录可以访问白名单页面
  42. if (whiteList.indexOf(to.path) !== -1) {
  43. // const dictStore = useDictionaryStore();
  44. // dictStore.checkDicts();
  45. next();
  46. } else {
  47. if (to.path === "/login") {
  48. next();
  49. } else {
  50. next(`/login`);
  51. }
  52. NProgress.done();
  53. }
  54. }
  55. });
  56. router.afterEach(() => {
  57. NProgress.done();
  58. });
  59. }