index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * 路由配置
  3. */
  4. import Vue from 'vue';
  5. import NProgress from 'nprogress';
  6. import VueRouter from 'vue-router';
  7. import { WHITE_LIST, REDIRECT_PATH, LAYOUT_PATH } from '@/config/setting';
  8. import store from '@/store';
  9. import { getToken, setToken, getCurrentUser } from '@/utils/token-util';
  10. import { routes, getMenuRoutes } from './routes';
  11. import { changeRole } from '@/api/layout/index';
  12. Vue.use(VueRouter);
  13. const router = new VueRouter({
  14. base: window.__POWERED_BY_QIANKUN__ ? '/page-wms/' : '/wms/',
  15. routes,
  16. mode: 'history',
  17. scrollBehavior () {
  18. return { y: 0 };
  19. }
  20. });
  21. /**
  22. * 路由守卫
  23. */
  24. router.beforeEach((to, from, next) => {
  25. if (!from.path.includes(REDIRECT_PATH)) {
  26. NProgress.start();
  27. }
  28. // 判断是否登录
  29. if (getToken()) {
  30. // 还未注册动态路由则先获取
  31. if (!store.state.user.menus) {
  32. store
  33. .dispatch('user/fetchUserInfo')
  34. .then(({ menus, homePath, authoritiesRouter }) => {
  35. if (menus) {
  36. router.addRoute(
  37. getMenuRoutes([...menus, ...authoritiesRouter], homePath)
  38. );
  39. next({ ...to, replace: true });
  40. }
  41. })
  42. .catch((e) => {
  43. console.error(e);
  44. next();
  45. });
  46. } else {
  47. // console.log(router.getRoutes(), 'router', routes);
  48. if (routes.length >= router.getRoutes()?.length) {
  49. router.addRoute(
  50. getMenuRoutes([
  51. ...store.state.user.menus,
  52. ...store.state.user.authoritiesRouter,
  53. to.fullPath
  54. ])
  55. );
  56. next({ ...to });
  57. } else {
  58. next();
  59. }
  60. }
  61. } else if (WHITE_LIST.includes(to.path)) {
  62. next();
  63. } else {
  64. next({
  65. path: '/login',
  66. query: to.path === LAYOUT_PATH ? {} : { from: to.path }
  67. });
  68. }
  69. });
  70. router.afterEach((to) => {
  71. if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) {
  72. setTimeout(() => {
  73. NProgress.done(true);
  74. }, 200);
  75. }
  76. });
  77. router.roleChange = async ({ menus, homePath, authoritiesRouter }) => {
  78. const currentUser = getCurrentUser()
  79. if (menus && menus.length > 0) {
  80. router.addRoute(
  81. getMenuRoutes([...menus, ...authoritiesRouter], homePath)
  82. );
  83. if (router.currentRoute.path != (menus[0].redirect || menus[0].path)) {
  84. await router.replace({
  85. path: menus[0].redirect || menus[0].path,
  86. })
  87. }
  88. const newToken = await changeRole({ groupId: currentUser.currentGroupId, roleId: currentUser.currentRoleId })
  89. setToken(newToken)
  90. setTimeout(() => {
  91. window.location.reload()
  92. }, 100);
  93. }
  94. // next({ ...to, replace: true });
  95. };
  96. export default router;