feat: 架构调整

This commit is contained in:
2026-07-23 11:27:33 +08:00
parent 6f37264047
commit 3b5a908ee4
25 changed files with 653 additions and 245 deletions
+61 -2
View File
@@ -1,6 +1,9 @@
// src/hooks/useAuth.ts
import { useState } from './useState';
import { watch } from 'vue';
import { useMenuStore } from '@/stores/menuStore';
import { usePermissionStore } from '@/stores/permissionStore';
import router, { WHITE_LIST } from '@/router';
const TOKEN_KEY = 'MY_APP_AUTH_TOKEN';
@@ -15,20 +18,76 @@ function createAuth() {
}
});
const login = (newToken: string) => {
const isLoggedIn = () => !!token.value;
/**
* 登录:保存 token → 拉取菜单+权限 → 动态注册路由 → 跳转首页
*/
const login = async (newToken: string) => {
setToken(newToken);
const { loadMenu, homePath } = useMenuStore();
const { loadPermissions } = usePermissionStore();
// 并行拉取菜单和权限
await Promise.all([loadMenu(), loadPermissions()]);
// 跳转到首页(动态路由已注册完成)
router.push(homePath.value);
};
/**
* 退出:清除 token → 清除菜单+权限 → 清除动态路由 → 跳转登录页
*/
const logout = () => {
setToken(null);
const { clearMenu } = useMenuStore();
const { clearPermissions } = usePermissionStore();
clearMenu();
clearPermissions();
router.push('/login');
};
return {
token,
isLoggedIn: () => !!token.value,
isLoggedIn,
login,
logout,
};
}
export const auth = createAuth();
/**
* 路由守卫逻辑(由 router/guard.ts 使用)
* 判断逻辑:
* 1. 白名单路径 → 直接放行
* 2. 已登录但菜单未加载 → 加载菜单后放行
* 3. 已登录且菜单已加载 → 直接放行
* 4. 未登录 → 跳转 /login
*/
export async function handleRouteGuard(
toPath: string,
): Promise<{ allow: boolean; redirect?: string }> {
// 白名单直接放行
if (WHITE_LIST.includes(toPath) || toPath.match(/^\/:pathMatch/)) {
return { allow: true };
}
// 未登录
if (!auth.isLoggedIn()) {
return { allow: false, redirect: '/login' };
}
// 已登录但菜单未加载 → 先加载
const { loadMenu, loaded } = useMenuStore();
if (!loaded.value) {
const { loadPermissions } = usePermissionStore();
await Promise.all([loadMenu(), loadPermissions()]);
}
return { allow: true };
}