import store from '@/store'; import router from '@/router'; import { notification } from 'ant-design-vue'; import NProgress from 'nprogress'; import 'nprogress/nprogress.css'; NProgress.configure({ showSpinner: false }); const loginPath = '/login'; const defaultRoutePath = '/race/list'; const whiteList = ['Login', 'Index']; // 白名单保持不变 router.beforeEach(async(to, from, next) => { NProgress.start(); const tokens = window.localStorage.getItem("token"); /* 未登录情况下的路由拦截 */ if (!tokens) { // 修改判断逻辑,同时检查路由名称和路径 if (whiteList.includes(to.name) || to.path === '/Index') { next(); } else { next({ path: loginPath, query: { redirect: to.fullPath, }, }); } return; } /* 已登录情况下访问登录界面的处理 */ if (to.path === loginPath) { next(defaultRoutePath); return; } /* 已获取用户信息的情况 */ if (store.getters.permissions != null && store.getters.permissions !== "") { next(); NProgress.done(); return; } /* 未获取用户信息的情况 */ try { await store.dispatch('initUser'); } catch (e) { store.commit('logout'); next({ path: loginPath, query: { redirect: to.fullPath } }); notification.error({ message: '错误', description: '请求用户信息失败,请重试', }); NProgress.done(); return; } /* 成功获取用户信息的情况 */ if (!checkAccess(to)) { next({ path: defaultRoutePath, replace: true }); NProgress.done(); return; } const redirect = decodeURIComponent(from.query.redirect || to.path); if (redirect === to.path) { next({...to, replace: true }); } else { next(redirect); } NProgress.done(); }); router.afterEach(() => { NProgress.done(); }); function checkAccess(route) { const userPrivileges = store.state.user.userPrivileges == null ? 1 : store.state.user.userPrivileges; const requiredPrivileges = route.meta.auth; console.log(userPrivileges); if (!requiredPrivileges) { return true; } return requiredPrivileges.includes(userPrivileges); }