Files
mp-10579/src/router/index.ts
赵忠林 1856a611ce chore(config): 初始化项目配置文件
- 添加 .editorconfig 文件统一代码风格
- 配置 .env.development 环境变量文件
- 创建 .env.example 环境变量示例文件
- 设置 .eslintignore 忽略检查规则
- 配置 .eslintrc.js 代码检查规则
- 添加 .gitignore 文件忽略版本控制
- 设置 .prettierignore 忽略格式化规则
- 新增隐私政策HTML页面文件
- 创建API密钥编辑组件基础结构
2025-12-15 13:29:17 +08:00

87 lines
2.2 KiB
TypeScript

/**
* 路由配置
*/
import NProgress from 'nprogress';
import type { _RouteLocationBase } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { WHITE_LIST, REDIRECT_PATH, LAYOUT_PATH } from '@/config/setting';
import { useUserStore } from '@/store/modules/user';
import { getToken } from '@/utils/token-util';
import { routes, getMenuRoutes } from './routes';
// import { useTenantStore } from '@/store/modules/tenant';
NProgress.configure({
speed: 200,
minimum: 0.02,
trickleSpeed: 200,
showSpinner: false
});
const router = createRouter({
routes,
history: createWebHistory(),
scrollBehavior() {
return { top: 0 };
}
});
// 标记动态路由是否已经注册
let dynamicRoutesRegistered = false;
// 重置动态路由注册状态的函数
export function resetDynamicRoutes() {
dynamicRoutesRegistered = false;
}
/**
* 路由守卫
*/
router.beforeEach(async (to, from) => {
if (!from.path.includes(REDIRECT_PATH)) {
NProgress.start();
}
// 租户信息
// const tenantStore = useTenantStore();
// await tenantStore.fetchTenantInfo();
if (!getToken()) {
// 未登录跳转登录界面
if (!WHITE_LIST.includes(to.path)) {
return {
path: '/login',
query: to.path === LAYOUT_PATH ? {} : { from: to.path }
};
}
return;
}
// 注册动态路由
const userStore = useUserStore();
if (!userStore.menus && !dynamicRoutesRegistered) {
const { menus, homePath } = await userStore.fetchUserInfo();
if (menus) {
const menuRoute = getMenuRoutes(menus, homePath);
router.addRoute(menuRoute);
dynamicRoutesRegistered = true;
// 只有当访问根路径时才跳转到首页
if (to.path === LAYOUT_PATH) {
return { path: homePath || '/dashboard', replace: true };
}
// 对于其他路径,只有在路由确实不存在时才跳转
// 这避免了已存在页面的不必要跳转
return { ...to, replace: true };
}
}
});
router.afterEach((to) => {
if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) {
setTimeout(() => {
NProgress.done(true);
}, 200);
}
});
export default router;