/** * 路由配置(对齐 EOM) */ import Vue from 'vue'; import NProgress from 'nprogress'; import VueRouter from 'vue-router'; import { WHITE_LIST, REDIRECT_PATH, LAYOUT_PATH, SYSTEM_NAME, HOME_PATH, } from '@/config/setting'; import store from '@/store'; import { getToken, setToken, getCurrentUser } from '@/utils/token-util'; import { routes, getMenuRoutes } from './routes'; import { changeRole } from '@/api/layout'; Vue.use(VueRouter); const router = new VueRouter({ // 与 EOM 一致:乾坤 /page-hr/ ,独立 /hr/ base: window.__POWERED_BY_QIANKUN__ ? `/page-${SYSTEM_NAME}/` : `/${SYSTEM_NAME}/`, routes, mode: 'history', scrollBehavior() { return { y: 0 }; }, }); export function getAppRouterBase() { return router.options.base; } export function resetRouter() { const newRouter = new VueRouter({ base: window.__POWERED_BY_QIANKUN__ ? `/page-${SYSTEM_NAME}/` : `/${SYSTEM_NAME}/`, routes, mode: 'history', scrollBehavior() { return { y: 0 }; }, }); router.matcher = newRouter.matcher; router.options.base = newRouter.options.base; } /** * 路由守卫(对齐 EOM) */ router.beforeEach((to, from, next) => { if (!from.path.includes(REDIRECT_PATH)) { NProgress.start(); } if (getToken()) { // 还未注册动态路由则先获取 if (!store.state.user.menus) { store .dispatch('user/fetchUserInfo') .then(({ menus, homePath, authoritiesRouter }) => { if (menus) { router.addRoute( getMenuRoutes( [...menus, ...(authoritiesRouter || [])], homePath || HOME_PATH, ), ); next({ ...to, replace: true }); } else { // 与 EOM:无菜单时仍放行,避免卡死;侧栏由门户按 /page-hr 维护 next(); } }) .catch((e) => { console.error(e); next(); }); } else { // 热更新等导致动态路由丢失时补注册 if (routes.length >= router.getRoutes()?.length) { router.addRoute( getMenuRoutes( [ ...store.state.user.menus, ...(store.state.user.authoritiesRouter || []), ], HOME_PATH, ), ); next({ ...to }); } else { next(); } } } else if (WHITE_LIST.includes(to.path)) { next(); } else { next({ path: '/login', query: to.path === LAYOUT_PATH ? {} : { from: to.path }, }); } }); router.afterEach((to) => { if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) { setTimeout(() => { NProgress.done(true); }, 200); } }); router.roleChange = async ({ menus, homePath, authoritiesRouter }) => { const currentUser = getCurrentUser(); if (menus && menus.length > 0) { router.addRoute( getMenuRoutes([...menus, ...(authoritiesRouter || [])], homePath), ); if ( router.currentRoute.path != (menus[0].redirect || menus[0].path) ) { await router.replace({ path: menus[0].redirect || menus[0].path, }); } const newToken = await changeRole({ groupId: currentUser.currentGroupId, roleId: currentUser.currentRoleId, }); setToken(newToken); setTimeout(() => { window.location.reload(); }, 100); } }; export function getRouter() { return router; } export default router;