import { createRouter, createWebHistory } from "vue-router"; import { routes } from "./routes"; import { useUserStore } from "@/store/user"; import { ElMessage } from "element-plus"; import { useTabStore } from "@/store/tab"; import NProgress from "nprogress"; import { usePermissionStore } from "@/store/permission"; NProgress.configure({ easing: "ease", speed: 500 }); const router = createRouter({ history: createWebHistory(import.meta.env.PUBLIC_SERVER_PATH || "/"), routes, }); router.beforeEach(async (to) => { NProgress?.start?.(); const userStore = useUserStore(); const permissionStore = usePermissionStore(); if (to.path === "/login") { if (userStore.isLogined()) { return "/"; } return true; } if (!userStore.isLogined() && to.path !== "/login") { ElMessage.warning("登录已过期,请先登录"); return "/login"; } // 检查权限 if (to.meta.moduleId) { await permissionStore.init(); const hasPermission = permissionStore.hasModulePermission(to.meta.moduleId); if (!hasPermission) { ElMessage.warning("您没有权限访问此页面"); return "/"; } } // 处理 tab 页路径 handleTabPath(to); return true; }); router.afterEach(() => { NProgress?.done?.(); }); function handleTabPath(to) { const path = to.path; if (path === "/login") { return; } const meta = to.meta; const query = to.query; // 处理标签页 if (meta.title) { let displayTitle = meta.title; if (query.id) { displayTitle = `${meta.title} ${query.id}`; } const tabStore = useTabStore(); tabStore.addTab({ path: path, fullPath: to.fullPath, title: displayTitle, params: to.params, meta: to.meta, query: to.query, }); } } export default router;