index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 } from '@/utils/token-util';
  10. import { routes, getMenuRoutes } from './routes';
  11. Vue.use(VueRouter);
  12. const router = new VueRouter({
  13. base: window.__POWERED_BY_QIANKUN__ ? '/page-wms/' : '/wms/',
  14. routes,
  15. mode: 'history',
  16. scrollBehavior () {
  17. return { y: 0 };
  18. }
  19. });
  20. /**
  21. * 路由守卫
  22. */
  23. router.beforeEach((to, from, next) => {
  24. if (!from.path.includes(REDIRECT_PATH)) {
  25. NProgress.start();
  26. }
  27. // 判断是否登录
  28. if (getToken()) {
  29. // 还未注册动态路由则先获取
  30. if (!store.state.user.menus) {
  31. store
  32. .dispatch('user/fetchUserInfo')
  33. .then(({ menus, homePath, authoritiesRouter }) => {
  34. if (menus) {
  35. router.addRoute(
  36. getMenuRoutes([...menus, ...authoritiesRouter], homePath)
  37. );
  38. next({ ...to, replace: true });
  39. }
  40. })
  41. .catch((e) => {
  42. console.error(e);
  43. next();
  44. });
  45. } else {
  46. // console.log(router.getRoutes(), 'router', routes);
  47. if (routes.length >= router.getRoutes()?.length) {
  48. router.addRoute(
  49. getMenuRoutes([
  50. ...store.state.user.menus,
  51. ...store.state.user.authoritiesRouter,
  52. to.fullPath
  53. ])
  54. );
  55. next({ ...to });
  56. } else {
  57. next();
  58. }
  59. }
  60. } else if (WHITE_LIST.includes(to.path)) {
  61. next();
  62. } else {
  63. next({
  64. path: '/login',
  65. query: to.path === LAYOUT_PATH ? {} : { from: to.path }
  66. });
  67. }
  68. });
  69. router.afterEach((to) => {
  70. if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) {
  71. setTimeout(() => {
  72. NProgress.done(true);
  73. }, 200);
  74. }
  75. });
  76. export default router;