Commit 5dad50e0 by Lin

fix: 代码结构优化

1 parent d00917d4
...@@ -168,7 +168,7 @@ const handleCurrentChange = (val) => { ...@@ -168,7 +168,7 @@ const handleCurrentChange = (val) => {
<template> <template>
<div class="min-h-screen bg-white p-5"> <div class="min-h-screen bg-white p-5">
<!-- 1. 顶部标题 --> <!-- 1. 顶部标题 -->
<h2 class="mb-5 text-lg font-semibold text-[#303133]">岗位助理配置</h2> <h2 class="mb-5 text-lg font-semibold text-[#303133]">岗位助理配置测试</h2>
<!-- 2. 搜索区域 --> <!-- 2. 搜索区域 -->
<div class="mb-5"> <div class="mb-5">
...@@ -196,20 +196,20 @@ const handleCurrentChange = (val) => { ...@@ -196,20 +196,20 @@ const handleCurrentChange = (val) => {
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item class="ml-[-8px]"> <el-form-item class="ml-[-8px]">
<!-- <el-button class="search-btn" @click="handleSearch">查询</el-button> <el-button class="search-btn w-[60px] h-8" @click="handleSearch">查询</el-button>
<el-button @click="handleReset">重置</el-button> --> <el-button class="w-[60px] h-8" @click="handleReset">重置</el-button>
<div <!-- <div
class="search-btn-custom w-[60px] h-8 rounded-[5px] border border-[#8baefe] bg-white flex items-center justify-center cursor-pointer text-[#1956FE] transition-all duration-200" class="search-btn-custom w-[60px] h-8 rounded-[5px] border border-[#8baefe] bg-white flex items-center justify-center cursor-pointer text-[#1956FE] transition-all duration-200"
@click="handleSearch" @click="handleSearch"
> >
查询 查询
</div> </div> -->
<div <!-- <div
class="reset-btn-custom w-[60px] h-8 rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] ml-2 transition-all duration-200" class="reset-btn-custom w-[60px] h-8 rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] ml-2 transition-all duration-200"
@click="handleReset" @click="handleReset"
> >
重置 重置
</div> </div> -->
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
*/ */
import type { MenuItem, TopMenuItem } from '@/types/menu'; import type { MenuItem, TopMenuItem } from '@/types/menu';
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
import { fetchMicroAppConfig } from '@/config/center';
/** /**
* 路由配置接口(从 API 返回的数据结构) * 路由配置接口(从 API 返回的数据结构)
*/ */
...@@ -53,12 +52,6 @@ export interface MenuConfig { ...@@ -53,12 +52,6 @@ export interface MenuConfig {
} }
/** /**
* 获取路由和菜单配置
* @returns Promise<路由和菜单配置>
*/
export const getRouteConfig = fetchMicroAppConfig;
/**
* 将 API 返回的路由配置转换为 Vue Router 路由格式 * 将 API 返回的路由配置转换为 Vue Router 路由格式
*/ */
export function transformRouteConfig(config: RouteConfig): RouteRecordRaw { export function transformRouteConfig(config: RouteConfig): RouteRecordRaw {
......
...@@ -40,7 +40,7 @@ function initConfigReadyPromise() { ...@@ -40,7 +40,7 @@ function initConfigReadyPromise() {
* 获取远程路由配置数据 * 获取远程路由配置数据
* @returns 路由数据 * @returns 路由数据
*/ */
export async function fetchMicroAppConfig(): Promise<any> { export async function fetchMicroAppRouteConfig(): Promise<any> {
// 先检查本地缓存 // 先检查本地缓存
const cachedData = localCache.get(ROUTER_CONFIG_CACHE_KEY); const cachedData = localCache.get(ROUTER_CONFIG_CACHE_KEY);
if (cachedData) { if (cachedData) {
......
...@@ -254,7 +254,6 @@ const handleMenuToggle = (menuId: string) => { ...@@ -254,7 +254,6 @@ const handleMenuToggle = (menuId: string) => {
// 判断是否为微应用路由 // 判断是否为微应用路由
const isMicroAppRoute = (path: string): boolean => { const isMicroAppRoute = (path: string): boolean => {
console.log('isMicroAppRoute',microApps);
return microApps.some((app) => { return microApps.some((app) => {
const rule = app.activeRule; const rule = app.activeRule;
if (typeof rule === 'string') { if (typeof rule === 'string') {
......
import { createApp } from 'vue'; import { createApp } from 'vue';
import { createPinia } from 'pinia'; import { createPinia } from 'pinia';
import App from './App.vue'; import App from './App.vue';
import { fetchConfig, getConfig } from './config/center'; import { fetchConfig } from './config/center';
import { setupQiankun } from './qiankun'; import { setupQiankun } from './qiankun';
import router, { loadDynamicRoutes } from './router'; import router, { loadDynamicRoutes } from './router';
import { useAppStore, useUserStore } from './stores'; import { useAppStore, useUserStore } from './stores';
...@@ -37,7 +37,7 @@ async function initApp() { ...@@ -37,7 +37,7 @@ async function initApp() {
// 尝试获取用户信息(如果失败,路由守卫会处理) // 尝试获取用户信息(如果失败,路由守卫会处理)
try { try {
await userStore.getUserInfo(); await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单 // 用户信息获取成功后,加载动态路由和菜单-性能优化层(预加载)- 有必要性
await loadDynamicRoutes(); await loadDynamicRoutes();
} catch { } catch {
// console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录'); // console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
...@@ -72,7 +72,7 @@ function setupStoreSync() { ...@@ -72,7 +72,7 @@ function setupStoreSync() {
// 获取配置中心配置 // 获取配置中心配置
fetchConfig() fetchConfig()
.then((config) => { .then((config) => {
console.log('[基座] 当前配置数据:', getConfig(), config); console.log('[基座] 当前配置数据:', config);
}) })
.catch((error) => { .catch((error) => {
console.error('[基座] 配置中心配置获取失败:', error); console.error('[基座] 配置中心配置获取失败:', error);
......
import type { MicroAppConfig } from './types'; // 微应用配置类型 import type { MicroAppConfig } from './types'; // 微应用配置类型
import { fetchMicroAppConfig } from '@/config/center'; import { fetchMicroAppRouteConfig } from '../config/center';
import { transformRemoteConfigToQiankunConfig } from './configTransformer'; import { transformToQiankun } from './configTransformer';
// 微应用配置列表(初始为空,后续动态加载) // 微应用配置列表(初始为空,后续动态加载)
export let microApps: MicroAppConfig[] = []; export let microApps: MicroAppConfig[] = [];
...@@ -31,10 +31,10 @@ export async function loadMicroAppConfig(): Promise<void> { ...@@ -31,10 +31,10 @@ export async function loadMicroAppConfig(): Promise<void> {
// 保证“配置加载”件事只被触发一次,并让后续调用都能等待同一个异步结果 // 保证“配置加载”件事只被触发一次,并让后续调用都能等待同一个异步结果
configLoadPromise = (async () => { configLoadPromise = (async () => {
try { try {
const remoteConfig = await fetchMicroAppConfig(); const remoteConfig = await fetchMicroAppRouteConfig();
// 获取子应用路由配置,并转换远程配置为 qiankun 配置( // 获取子应用路由配置,并转换远程配置为 qiankun 配置(
// props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa // props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa
microApps = transformRemoteConfigToQiankunConfig(remoteConfig.data?.microApps); microApps = transformToQiankun(remoteConfig.data?.microApps);
// 如果远程配置为空,使用默认配置 // 如果远程配置为空,使用默认配置
if (microApps.length === 0) { if (microApps.length === 0) {
microApps = defaultMicroApps; microApps = defaultMicroApps;
......
...@@ -54,7 +54,7 @@ function resolveEntry(entry: string | RemoteAppEntry): string { ...@@ -54,7 +54,7 @@ function resolveEntry(entry: string | RemoteAppEntry): string {
* 转换远程配置为 qiankun 配置 * 转换远程配置为 qiankun 配置
* @param remoteMicroApps 远程微应用配置数组 * @param remoteMicroApps 远程微应用配置数组
*/ */
export function transformRemoteConfigToQiankunConfig( export function transformToQiankun(
remoteMicroApps?: RemoteMicroApp[], remoteMicroApps?: RemoteMicroApp[],
): MicroAppConfig[] { ): MicroAppConfig[] {
// 如果没有传入配置或为空数组,返回空数组 // 如果没有传入配置或为空数组,返回空数组
......
...@@ -36,14 +36,15 @@ const qiankunConfig = { ...@@ -36,14 +36,15 @@ const qiankunConfig = {
}; };
/** /**
* @desc 初始化并启动 qiankun * @desc 初始化并启动 qiankun-每次刷新也没有均会调用此方法
*/ */
export async function setupQiankun() { export async function setupQiankun() {
// 先加载微应用配置(包含运行时依赖注入) // 先加载微应用配置(包含运行时依赖注入)
// 保证microApps配置加载完成后再进行后续初始化 // 保证microApps配置加载完成后再进行后续初始化
await loadMicroAppConfig(); await loadMicroAppConfig(); //首次调用微应用路由配置
// 1. 初始化通信管理器 // 1. 初始化通信管理器
communicationManager.init(); communicationManager.init();
registerMicroApps(microApps, microAppLifecycles); registerMicroApps(microApps, microAppLifecycles);
// 3. 添加全局错误处理 // 3. 添加全局错误处理
......
...@@ -8,7 +8,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -8,7 +8,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
* 微应用加载前 * 微应用加载前
*/ */
beforeLoad: async (app) => { beforeLoad: async (app) => {
console.log('[qiankun] before load', app); console.log('微应用加载前', app);
// 显示加载状态 // 显示加载状态
try { try {
const { useAppStore } = await import('@/stores'); const { useAppStore } = await import('@/stores');
...@@ -23,7 +23,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -23,7 +23,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
* 微应用挂载前 * 微应用挂载前
*/ */
beforeMount: async (app) => { beforeMount: async (app) => {
console.log('[qiankun] before mount', app); console.log('微应用挂载前', app);
// 确保主应用的数据已准备好并同步到全局状态 // 确保主应用的数据已准备好并同步到全局状态
try { try {
const { communicationManager } = await import('./communication'); const { communicationManager } = await import('./communication');
...@@ -69,7 +69,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -69,7 +69,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
* 微应用挂载后 * 微应用挂载后
*/ */
afterMount: async (app) => { afterMount: async (app) => {
console.log('[qiankun] before mount', app); console.log('微应用挂载后', app);
// 隐藏加载状态 // 隐藏加载状态
try { try {
const { useAppStore } = await import('@/stores'); const { useAppStore } = await import('@/stores');
...@@ -84,7 +84,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -84,7 +84,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
* 微应用卸载前 * 微应用卸载前
*/ */
beforeUnmount: async (app) => { beforeUnmount: async (app) => {
console.log('[qiankun] before unmount', app); console.log('微应用卸载前', app);
// 可以在这里做一些卸载前的清理工作 // 可以在这里做一些卸载前的清理工作
// 例如:保存状态、显示卸载动画等 // 例如:保存状态、显示卸载动画等
}, },
...@@ -93,7 +93,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -93,7 +93,7 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
* 微应用卸载后 * 微应用卸载后
*/ */
afterUnmount: async (app) => { afterUnmount: async (app) => {
console.log('[qiankun] after unmount', app); console.log('微应用卸载后', app);
// 确保清除加载状态 // 确保清除加载状态
try { try {
const { useAppStore } = await import('@/stores'); const { useAppStore } = await import('@/stores');
......
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router'; import { createRouter, createWebHistory } from 'vue-router';
import { ElMessage } from 'element-plus'; import { ElMessage } from 'element-plus';
import { getRouteConfig, transformMenuConfig, type MenuConfig } from '@/api/route'; import { transformMenuConfig, type MenuConfig } from '@/api/route';
import { fetchMicroAppRouteConfig } from '../config/center';
import { getMicroAppByPath } from '@/qiankun/apps'; import { getMicroAppByPath } from '@/qiankun/apps';
import { useAppStore, useMenuStore, useUserStore } from '@/stores'; import { useAppStore, useMenuStore, useUserStore } from '@/stores';
import { getToken } from '@/utils/auth'; import { getToken } from '@/utils/auth';
...@@ -89,7 +90,7 @@ export function addRoutes(routes: RouteRecordRaw[], parentName?: string) { ...@@ -89,7 +90,7 @@ export function addRoutes(routes: RouteRecordRaw[], parentName?: string) {
.find((route) => route.name === parentName); .find((route) => route.name === parentName);
if (parentRoute) { if (parentRoute) {
routes.forEach((route) => { routes.forEach((route) => {
console.log('[路由] addRoute', route); // console.log('[路由] addRoute', route);
router.addRoute(parentName, route); router.addRoute(parentName, route);
}); });
} else { } else {
...@@ -103,14 +104,6 @@ export function addRoutes(routes: RouteRecordRaw[], parentName?: string) { ...@@ -103,14 +104,6 @@ export function addRoutes(routes: RouteRecordRaw[], parentName?: string) {
} }
} }
/**
* 动态添加子路由到 Layout
* @param routes 要添加的路由配置数组
*/
export function addLayoutRoutes(routes: RouteRecordRaw[]) {
addRoutes(routes, 'Layout');
}
// 白名单:不需要登录的路由 // 白名单:不需要登录的路由
const whiteList = new Set(['/forgot-password', '/login', '/register']); const whiteList = new Set(['/forgot-password', '/login', '/register']);
...@@ -133,7 +126,7 @@ export async function loadDynamicRoutes() { ...@@ -133,7 +126,7 @@ export async function loadDynamicRoutes() {
try { try {
isLoadingRoutes = true; isLoadingRoutes = true;
// 调用 API 获取路由和菜单配置 // 调用 API 获取路由和菜单配置
const response = await getRouteConfig(); const response = await fetchMicroAppRouteConfig();
if (response.code === 200 && response.data) { if (response.code === 200 && response.data) {
const routerData: MenuConfig = { const routerData: MenuConfig = {
topMenus: [], topMenus: [],
...@@ -151,7 +144,7 @@ export async function loadDynamicRoutes() { ...@@ -151,7 +144,7 @@ export async function loadDynamicRoutes() {
// 动态添加路由到 Layout 的 children 中 // 动态添加路由到 Layout 的 children 中
if (routes.length > 0) { if (routes.length > 0) {
addLayoutRoutes(routes); addRoutes(routes, 'Layout')
menuStore.addDynamicRoutes(routes); menuStore.addDynamicRoutes(routes);
} }
} }
...@@ -181,15 +174,15 @@ async function isPossibleMicroAppPath(path: string): Promise<boolean> { ...@@ -181,15 +174,15 @@ async function isPossibleMicroAppPath(path: string): Promise<boolean> {
* @param targetPath 目标路径 * @param targetPath 目标路径
*/ */
async function waitForRoutesAndRematch(targetPath: string): Promise<boolean> { async function waitForRoutesAndRematch(targetPath: string): Promise<boolean> {
const appStore = useAppStore();
const menuStore = useMenuStore(); const menuStore = useMenuStore();
// 如果已经加载过,检查路由是否匹配 // 如果已经加载过,直接检查路由是否匹配,不再重复加载
if (menuStore.isMenusLoaded) { if (menuStore.isMenusLoaded) {
const matchedRoutes = router.resolve(targetPath); const matchedRoutes = router.resolve(targetPath);
return matchedRoutes.name !== 'NotFound'; return matchedRoutes.name !== 'NotFound';
} }
const appStore = useAppStore();
// 显示 loading // 显示 loading
appStore.setLoading(true); appStore.setLoading(true);
...@@ -232,6 +225,10 @@ router.beforeEach(async (to, _from, next) => { ...@@ -232,6 +225,10 @@ router.beforeEach(async (to, _from, next) => {
// 如果匹配到404路由,检查是否是子应用路由 // 如果匹配到404路由,检查是否是子应用路由
if (to.name === 'NotFound' && token) { if (to.name === 'NotFound' && token) {
const menuStore = useMenuStore();
// 优化:如果动态路由还未加载,才进行检查和加载
if (!menuStore.isMenusLoaded) {
// 检查当前路径是否可能是子应用路由(等待配置加载完成) // 检查当前路径是否可能是子应用路由(等待配置加载完成)
const isMicroAppPath = await isPossibleMicroAppPath(to.path); const isMicroAppPath = await isPossibleMicroAppPath(to.path);
...@@ -248,13 +245,13 @@ router.beforeEach(async (to, _from, next) => { ...@@ -248,13 +245,13 @@ router.beforeEach(async (to, _from, next) => {
// 路由已匹配,重新导航到目标路径 // 路由已匹配,重新导航到目标路径
next({ path: to.path, replace: true }); next({ path: to.path, replace: true });
return; return;
} else {
// 确实不存在,显示404页面
next();
return;
} }
} }
} }
// 动态路由已加载但仍是404,或不是微应用路由,显示404页面
next();
return;
}
if (token) { if (token) {
// 已登录 // 已登录
...@@ -264,8 +261,6 @@ router.beforeEach(async (to, _from, next) => { ...@@ -264,8 +261,6 @@ router.beforeEach(async (to, _from, next) => {
} else { } else {
// 检查是否已获取用户信息 // 检查是否已获取用户信息
if (userStore.userInfo) { if (userStore.userInfo) {
// 确保动态路由已加载
await loadDynamicRoutes();
// 检查权限 // 检查权限
if (to.meta.permissions || to.meta.roles) { if (to.meta.permissions || to.meta.roles) {
...@@ -348,7 +343,7 @@ router.beforeEach(async (to, _from, next) => { ...@@ -348,7 +343,7 @@ router.beforeEach(async (to, _from, next) => {
* 全局后置守卫 * 全局后置守卫
*/ */
router.afterEach((to, from) => { router.afterEach((to, from) => {
console.log('[路由] afterEach', to, from); // console.log('[路由] afterEach', to, from);
// 路由跳转完成后的处理 // 路由跳转完成后的处理
// console.log(`[路由] 从 ${from.path} 跳转到 ${to.path}`); // console.log(`[路由] 从 ${from.path} 跳转到 ${to.path}`);
}); });
......
...@@ -126,7 +126,6 @@ export const useUserStore = defineStore('user', () => { ...@@ -126,7 +126,6 @@ export const useUserStore = defineStore('user', () => {
import('@/qiankun/communication') import('@/qiankun/communication')
.then(({ communicationManager }) => { .then(({ communicationManager }) => {
if (userInfo.value) { if (userInfo.value) {
console.log('syncUserToQiankun.value', userInfo.value);
communicationManager.updateUser({ communicationManager.updateUser({
id: userInfo.value.id, id: userInfo.value.id,
name: userInfo.value.name, name: userInfo.value.name,
......
<script setup lang="ts"> <script setup lang="ts">
import type { LoginParams } from '@/types/user'; import type { LoginParams } from '@/types/user';
import { computed, onMounted, reactive, ref, watch } from 'vue'; import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { GLInput,GLButton } from '@venus/common-ui-vue'; import { GLInput,GLButton } from '@venus/common-ui-vue';
import { getCaptcha } from '@/api/user'; import { getCaptcha } from '@/api/user';
import { useUserStore } from '@/stores'; import { useUserStore } from '@/stores';
...@@ -112,7 +112,6 @@ const handleLogin = async () => { ...@@ -112,7 +112,6 @@ const handleLogin = async () => {
try { try {
const result = await userStore.login(requestData); const result = await userStore.login(requestData);
let { code, msg } = result.data; let { code, msg } = result.data;
console.log("result",result);
if (code == 0) { if (code == 0) {
// 登录成功,处理记住密码逻辑 // 登录成功,处理记住密码逻辑
if (loginForm.rememberMe) { if (loginForm.rememberMe) {
...@@ -129,7 +128,7 @@ const handleLogin = async () => { ...@@ -129,7 +128,7 @@ const handleLogin = async () => {
// 登录成功,getUserInfo 已在 login 方法中自动调用 // 登录成功,getUserInfo 已在 login 方法中自动调用
ElMessage.success('登录成功'); ElMessage.success('登录成功');
// 加载动态路由和菜单(确保路由和菜单都被加载) // 加载动态路由和菜单(确保路由和菜单都被加载)-业务必需层(登录后加载)
await loadDynamicRoutes(); await loadDynamicRoutes();
// 获取默认跳转路径 // 获取默认跳转路径
const defaultPath = getFirstSubAppFirstMenuPath(); const defaultPath = getFirstSubAppFirstMenuPath();
...@@ -795,7 +794,6 @@ onMounted(() => { ...@@ -795,7 +794,6 @@ onMounted(() => {
margin-top: 20px; margin-top: 20px;
font-size: $font-size-lg !important; font-size: $font-size-lg !important;
font-weight: 600 !important; font-weight: 600 !important;
color: #fff !important;
border: none !important; border: none !important;
border-radius: $border-radius !important; border-radius: $border-radius !important;
box-shadow: none !important; box-shadow: none !important;
......
...@@ -11,10 +11,6 @@ ...@@ -11,10 +11,6 @@
pnpm build pnpm build
# 构建特定应用 # 构建特定应用
pnpm build:antd # Ant Design Vue 版本
pnpm build:ele # Element Plus 版本
pnpm build:naive # Naive UI 版本
pnpm build:play # Playground
pnpm build:docs # 文档 pnpm build:docs # 文档
``` ```
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!