import { createRouter, createWebHistory } from 'vue-router' import NProgress from '@/config/progress' import index from './modules' import { useAuthStore } from '@/stores/modules/auth' import { useCachedViewStore } from '@/stores/modules/cachedView' import { getQueryString } from '@/utils' const router = createRouter({ history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH), scrollBehavior: () => ({ left: 0, top: 0 }), routes: index }) // 白名单地址 const whileList = ['/401', '/403', '/404', '/500', '/preview'] router.beforeEach(async (to, from, next) => { const authStore = useAuthStore() const cachedViewStore = useCachedViewStore() // 添加缓存 cachedViewStore.addCached(to) // 进度条开始 NProgress.start() // 动态设置标题 const title = import.meta.env.VITE_GLOB_APP_TITLE document.title = to.meta.title ? `${to.meta.title} - ${title}` : title const token = getQueryString(window.location.href,"token") if(token){ next() }else{ // 是否为跳转登录页 if (to.path.toLocaleLowerCase() === '/login') { if (authStore.tokenGet) { // 哪来回哪去 return next(from.fullPath) } return next() } // 白名单中的路由直接放行 if (whileList.includes(to.path)) { return next() } // 不携带token的情况下,跳转到登录页 if (!authStore.tokenGet) { next({ path: `/login?redirect=${to.fullPath}`, replace: true }) return } // 获取用户信息 if (!authStore.usernameGet) { await authStore.getInfo() } next() } }) router.afterEach(() => { NProgress.done() }) router.onError(() => { NProgress.done() }) export default router