permission.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. router.beforeEach(async (to, from, next) => {
  12. NProgress.start();
  13. isNewVersion();
  14. const hasToken = localStorage.getItem("token");
  15. if (hasToken) {
  16. if (to.path === "/login") {
  17. // 如果已登录,跳转首页
  18. next({ path: "/" });
  19. NProgress.done();
  20. } else {
  21. // 如果已经登录,让菜单加载本地的写死路由的数据
  22. const userStore = usePermissionStore();
  23. if (!userStore.routes || userStore.routes.length === 0) {
  24. userStore.setRoutes(configRoutes);
  25. }
  26. const dictStore = useDictionaryStore();
  27. if (
  28. !dictStore.dicts.value ||
  29. JSON.stringify(dictStore.dicts.value) === "{}"
  30. ) {
  31. const res = await getUserDicts(dictStore.types);
  32. if (res.data) {
  33. dictStore.dicts = res?.data;
  34. }
  35. }
  36. next();
  37. }
  38. } else {
  39. // 未登录可以访问白名单页面
  40. if (whiteList.indexOf(to.path) !== -1) {
  41. // const dictStore = useDictionaryStore();
  42. // dictStore.checkDicts();
  43. next();
  44. } else {
  45. if (to.path === "/login") {
  46. next();
  47. } else {
  48. next(`/login`);
  49. }
  50. NProgress.done();
  51. }
  52. }
  53. });
  54. router.afterEach(() => {
  55. NProgress.done();
  56. });
  57. }