/** * @Description: 路由权限 * @Author: zenghua.wang * @Date: 2022-01-26 22:04:31 * @LastEditors: zenghua.wang * @LastEditTime: 2024-05-22 13:36:31 */ import NProgress from 'nprogress'; import 'nprogress/nprogress.css'; import router from '@/router'; import { useUserStore } from '@/store/modules/user'; import { usePermissionStore } from '@/store/modules/permission'; NProgress.configure({ showSpinner: false }); const { VITE_APP_TITLE } = import.meta.env; const whiteList = ['/login']; router.beforeEach(async (to, from, next) => { NProgress.start(); if (typeof to.meta.title === 'string') { document.title = VITE_APP_TITLE + ' | ' + to.meta.title; } const userStore = useUserStore(); const hasToken = userStore.hasToken(); console.log('main', hasToken); if (hasToken) { if (to.path === '/login') { next({ path: '/' }); } else { try { const PermissionStore = usePermissionStore(); if (!PermissionStore.routes.length) { const accessRoutes = await PermissionStore.generateRoutes(userStore.roles); accessRoutes.forEach((item) => router.addRoute(item)); return next({ ...to, replace: true }); } else { if (from.path.includes('/sub') && (!to.path.includes('/sub') || to.path.includes('/platform'))) { NProgress.done(); window.location.reload(); return; } next(); } } catch (error) { next(`/login?redirect=${to.path}`); } } } else { if (whiteList.indexOf(to.path) !== -1) { next(); } else { next(`/login?redirect=${to.path}`); } } }); router.afterEach(() => { NProgress.done(); });