index.js 2.3 KB

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