Commit 45e4de3d by Lin

feat:配置文件修改

1 parent 400b5a3e
Showing 202 changed files with 1291 additions and 1495 deletions
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 使用 commitlint 检查提交信息格式
npx --no -- commitlint --edit "$1"
# 运行代码格式化
pnpm format
# 运行 lint 检查
pnpm lint
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 运行类型检查
pnpm check:type
# 运行单元测试
pnpm test:unit
<div align="center"> Venus
<a href="https://github.com/anncwb/vue-venus-admin">
<img alt="venusAdmin Logo" width="215" src="https://unpkg.com/@venusjs/static-source@0.1.7/source/logo-v1.webp">
</a>
<br>
<br>
[![license](https://img.shields.io/github/license/anncwb/vue-venus-admin.svg)](LICENSE)
<h1>Vue venus Admin</h1>
</div>
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=venusjs_vue-venus-admin&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=venusjs_vue-venus-admin) ![codeql](https://github.com/venusjs/vue-venus-admin/actions/workflows/codeql.yml/badge.svg) ![build](https://github.com/venusjs/vue-venus-admin/actions/workflows/build.yml/badge.svg) ![ci](https://github.com/venusjs/vue-venus-admin/actions/workflows/ci.yml/badge.svg) ![deploy](https://github.com/venusjs/vue-venus-admin/actions/workflows/deploy.yml/badge.svg)
**中文** | [English](./README.md) | [日本語](./README.ja-JP.md)
## 简介
Vue venus Admin 是 Vue venus Admin 的升级版本。作为一个免费开源的中后台模板,它采用了最新的 Vue 3、Vite、TypeScript 等主流技术开发,开箱即用,可用于中后台前端开发,也适合学习参考。
## 升级提示
该版本为最新版本 `5.0`,与其他版本不兼容,如果你是新项目,建议使用最新版本。如果你想查看旧版本,请使用 [v2 分支](https://github.com/venusjs/vue-venus-admin/tree/v2)
## 特性
- **最新技术栈**:使用 Vue3/vite 等前端前沿技术开发
- **TypeScript**:应用程序级 JavaScript 的语言
- **主题**:提供多套主题色彩,可配置自定义主题
- **国际化**:内置完善的国际化方案
- **权限**:内置完善的动态路由权限生成方案
## 预览
- [venus Admin](https://venus.pro/) - 完整版中文站点
测试账号:venus/123456
<div align="center">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview1.png">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview2.png">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview3.png">
</div>
### 使用 Gitpod
在 Gitpod(适用于 GitHub 的免费在线开发环境)中打开项目,并立即开始编码。
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/venusjs/vue-venus-admin)
## 文档
[文档地址](https://doc.venus.pro/)
## 安装使用
1. 获取项目代码
```bash
git clone https://github.com/venusjs/vue-venus-admin.git
```
2. 安装依赖
```bash
cd vue-venus-admin
npm i -g corepack
pnpm install
```
3. 运行
```bash
pnpm dev
```
4. 打包
```bash
pnpm build
```
## 更新日志
[CHANGELOG](https://github.com/venusjs/vue-venus-admin/releases)
## 如何贡献
非常欢迎你的加入![提一个 Issue](https://github.com/anncwb/vue-venus-admin/issues/new/choose) 或者提交一个 Pull Request。
**Pull Request 流程:**
1. Fork 代码
2. 创建自己的分支:`git checkout -b feature/xxxx`
3. 提交你的修改:`git commit -am 'feat(function): add xxxxx'`
4. 推送您的分支:`git push origin feature/xxxx`
5. 提交 `pull request`
## Git 贡献提交规范
参考 [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) 规范 ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular))
- `feat` 增加新功能
- `fix` 修复问题/BUG
- `style` 代码风格相关无影响运行结果的
- `perf` 优化/性能提升
- `refactor` 重构
- `revert` 撤销修改
- `test` 测试相关
- `docs` 文档/注释
- `chore` 依赖更新/脚手架配置修改等
- `ci` 持续集成
- `types` 类型定义文件更改
## 浏览器支持
本地开发推荐使用 `Chrome 80+` 浏览器
支持现代浏览器,不支持 IE
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari |
| :-: | :-: | :-: | :-: |
| last 2 versions | last 2 versions | last 2 versions | last 2 versions |
## 维护者
[@venus](https://github.com/anncwb)
## Star 历史
[![Star History Chart](https://api.star-history.com/svg?repos=venusjs/vue-venus-admin&type=Date)](https://star-history.com/#venusjs/vue-venus-admin&Date)
## 捐赠
如果你觉得这个项目对你有帮助,你可以帮作者买一杯咖啡表示支持!
![donate](https://unpkg.com/@venusjs/static-source@0.1.7/source/sponsor.png)
<a style="display: block;width: 100px;height: 50px;line-height: 50px; color: #fff;text-align: center; background: #408aed;border-radius: 4px;" href="https://www.paypal.com/paypalme/cvvenus">Paypal Me</a>
## 贡献者
<a href="https://openomy.app/github/venusjs/vue-venus-admin" target="_blank" style="display: block; width: 100%;" align="center">
<img src="https://openomy.app/svg?repo=venusjs/vue-venus-admin&chart=bubble&latestMonth=3" target="_blank" alt="Contribution Leaderboard" style="display: block; width: 100%;" />
</a>
<a href="https://github.com/venusjs/vue-venus-admin/graphs/contributors">
<img alt="Contributors" src="https://contrib.rocks/image?repo=venusjs/vue-venus-admin" />
</a>
## Discord
- [Github Discussions](https://github.com/anncwb/vue-venus-admin/discussions)
## 许可证
[MIT © venus-2020](./LICENSE)
<div align="center"> Venus
<a href="https://github.com/anncwb/vue-venus-admin">
<img alt="venusAdmin Logo" width="215" src="https://unpkg.com/@venusjs/static-source@0.1.7/source/logo-v1.webp">
</a>
<br>
<br>
[![license](https://img.shields.io/github/license/anncwb/vue-venus-admin.svg)](LICENSE)
<h1>Vue venus Admin</h1>
</div>
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=venusjs_vue-venus-admin&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=venusjs_vue-venus-admin) [![codeql](https://github.com/venusjs/vue-venus-admin/actions/workflows/codeql.yml/badge.svg)](https://github.com/venusjs/vue-venus-admin/actions/workflows/codeql.yml) [![build](https://github.com/venusjs/vue-venus-admin/actions/workflows/build.yml/badge.svg)](https://github.com/venusjs/vue-venus-admin/actions/workflows/build.yml) [![ci](https://github.com/venusjs/vue-venus-admin/actions/workflows/ci.yml/badge.svg)](https://github.com/venusjs/vue-venus-admin/actions/workflows/ci.yml) [![deploy](https://github.com/venusjs/vue-venus-admin/actions/workflows/deploy.yml/badge.svg)](https://github.com/venusjs/vue-venus-admin/actions/workflows/deploy.yml)
**English** | [中文](./README.zh-CN.md) | [日本語](./README.ja-JP.md)
## Introduction
Vue venus Admin is a free and open source middle and back-end template. Using the latest `vue3`, `vite`, `TypeScript` and other mainstream technology development, the out-of-the-box middle and back-end front-end solutions can also be used for learning reference.
## Upgrade Notice
This is the latest version, 5.0, and it is not compatible with previous versions. If you are starting a new project, it is recommended to use the latest version. If you wish to view the old version, please use the [v2 branch](https://github.com/venusjs/vue-venus-admin/tree/v2).
## Features
- **Latest Technology Stack**: Developed with cutting-edge front-end technologies like Vue 3 and Vite
- **TypeScript**: A language for application-scale JavaScript
- **Themes**: Multiple theme colors available with customizable options
- **Internationalization**: Comprehensive built-in internationalization support
- **Permissions**: Built-in solution for dynamic route-based permission generation
## Preview
- [venus Admin](https://venus.pro/) - Full version Chinese site
Test Account: venus/123456
<div align="center">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview1.png">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview2.png">
<img alt="venusAdmin Logo" width="100%" src="https://anncwb.github.io/anncwb/images/preview3.png">
</div>
### Use Gitpod
Open the project in Gitpod (free online dev environment for GitHub) and start coding immediately.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/venusjs/vue-venus-admin)
## Documentation
[Document](https://doc.venus.pro/)
## Install and Use
1. Get the project code
```bash
git clone https://github.com/venusjs/vue-venus-admin.git
```
2. Install dependencies
```bash
cd vue-venus-admin
npm i -g corepack
pnpm install
```
3. Run
```bash
pnpm dev
```
4. Build
```bash
pnpm build
```
## Change Log
[CHANGELOG](https://github.com/venusjs/vue-venus-admin/releases)
## How to Contribute
You are very welcome to join! [Raise an issue](https://github.com/anncwb/vue-venus-admin/issues/new/choose) or submit a Pull Request.
**Pull Request Process:**
1. Fork the code
2. Create your branch: `git checkout -b feat/xxxx`
3. Submit your changes: `git commit -am 'feat(function): add xxxxx'`
4. Push your branch: `git push origin feat/xxxx`
5. Submit `pull request`
## Git Contribution Submission Specification
Reference [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) specification ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular))
- `feat` Add new features
- `fix` Fix the problem/BUG
- `style` The code style is related and does not affect the running result
- `perf` Optimization/performance improvement
- `refactor` Refactor
- `revert` Undo edit
- `test` Test related
- `docs` Documentation/notes
- `chore` Dependency update/scaffolding configuration modification etc.
- `ci` Continuous integration
- `types` Type definition file changes
## Browser Support
The `Chrome 80+` browser is recommended for local development
Support modern browsers, not IE
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari |
| :-: | :-: | :-: | :-: |
| last 2 versions | last 2 versions | last 2 versions | last 2 versions |
## Maintainer
[@venus](https://github.com/anncwb)
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=venusjs/vue-venus-admin&type=Date)](https://star-history.com/#venusjs/vue-venus-admin&Date)
## Donate
If you think this project is helpful to you, you can help the author buy a cup of coffee to show your support!
![donate](https://unpkg.com/@venusjs/static-source@0.1.7/source/sponsor.png)
<a style="display: block;width: 100px;height: 50px;line-height: 50px; color: #fff;text-align: center; background: #408aee;border-radius: 4px;" href="https://www.paypal.com/paypalme/cvvenus">Paypal Me</a>
## Contributors
<a href="https://openomy.app/github/venusjs/vue-venus-admin" target="_blank" style="display: block; width: 100%;" align="center">
<img src="https://openomy.app/svg?repo=venusjs/vue-venus-admin&chart=bubble&latestMonth=3" target="_blank" alt="Contribution Leaderboard" style="display: block; width: 100%;" />
</a>
<a href="https://github.com/venusjs/vue-venus-admin/graphs/contributors">
<img alt="Contributors" src="https://contrib.rocks/image?repo=venusjs/vue-venus-admin" />
</a>
## Discord
- [Github Discussions](https://github.com/anncwb/vue-venus-admin/discussions)
## License
[MIT © venus-2020](./LICENSE)
/// <reference types="vite/client" /> // / <reference types="vite/client" />
declare module '*.vue' { declare module '*.vue' {
import type { DefineComponent } from 'vue'; import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
...@@ -10,26 +10,25 @@ ...@@ -10,26 +10,25 @@
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"vue": "catalog:", "@element-plus/icons-vue": "catalog:",
"vue-router": "catalog:", "@venus/common-ui-vue": "workspace:*",
"pinia": "catalog:",
"qiankun": "catalog:",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"axios": "catalog:", "axios": "catalog:",
"@element-plus/icons-vue": "catalog:",
"element-plus": "catalog:", "element-plus": "catalog:",
"@venus/common-ui": "workspace:*" "pinia": "catalog:",
"qiankun": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:", "@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:", "@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:", "typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:",
"unplugin-auto-import": "catalog:", "unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:", "unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:", "vite-plugin-qiankun": "catalog:",
"@types/node": "catalog:" "vue-tsc": "catalog:"
} }
} }
<script setup lang="ts">
// 根组件入口
</script>
<template> <template>
<div id="main-app"> <div id="main-app">
<router-view /> <router-view />
</div> </div>
</template> </template>
<script setup lang="ts">
// 根组件入口
</script>
<style scoped> <style scoped>
#main-app { #main-app {
width: 100%; width: 100%;
...@@ -15,4 +15,3 @@ ...@@ -15,4 +15,3 @@
min-height: 100vh; min-height: 100vh;
} }
</style> </style>
...@@ -3,4 +3,3 @@ ...@@ -3,4 +3,3 @@
*/ */
export * from './user'; export * from './user';
...@@ -9,7 +9,7 @@ import type { LoginParams, LoginResponse, UserInfo } from '@/types/user'; ...@@ -9,7 +9,7 @@ import type { LoginParams, LoginResponse, UserInfo } from '@/types/user';
* 模拟延迟 * 模拟延迟
*/ */
const mockDelay = (ms: number = 500) => { const mockDelay = (ms: number = 500) => {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
}; };
/** /**
...@@ -72,10 +72,12 @@ const mockUsers = [ ...@@ -72,10 +72,12 @@ const mockUsers = [
/** /**
* 模拟登录 * 模拟登录
*/ */
export const mockLogin = async (data: LoginParams): Promise<ApiResponse<LoginResponse>> => { export const mockLogin = async (
data: LoginParams,
): Promise<ApiResponse<LoginResponse>> => {
await mockDelay(800); await mockDelay(800);
const user = mockUsers.find(u => u.username === data.username); const user = mockUsers.find((u) => u.username === data.username);
if (!user) { if (!user) {
return { return {
...@@ -124,12 +126,14 @@ export const mockLogout = async (): Promise<ApiResponse<void>> => { ...@@ -124,12 +126,14 @@ export const mockLogout = async (): Promise<ApiResponse<void>> => {
/** /**
* 模拟获取用户信息 * 模拟获取用户信息
*/ */
export const mockGetUserInfo = async (token: string): Promise<ApiResponse<UserInfo>> => { export const mockGetUserInfo = async (
token: string,
): Promise<ApiResponse<UserInfo>> => {
await mockDelay(500); await mockDelay(500);
// 从 token 中解析用户名 // 从 token 中解析用户名
const username = token.split('_')[2]; const username = token.split('_')[2];
const user = mockUsers.find(u => u.username === username); const user = mockUsers.find((u) => u.username === username);
if (!user) { if (!user) {
return { return {
...@@ -187,4 +191,3 @@ export const getUserInfo = () => { ...@@ -187,4 +191,3 @@ export const getUserInfo = () => {
`; `;
console.log(MOCK_API_USAGE); console.log(MOCK_API_USAGE);
...@@ -2,21 +2,22 @@ ...@@ -2,21 +2,22 @@
* 用户相关 API * 用户相关 API
*/ */
import { post, get } from '@/utils/request';
import type { ApiResponse } from '@/types/api'; import type { ApiResponse } from '@/types/api';
import type { import type {
LoginParams,
LoginResponse,
UserInfo,
ChangePasswordParams, ChangePasswordParams,
UpdateUserInfoParams LoginParams,
LoginResponse,
UpdateUserInfoParams,
UserInfo,
} from '@/types/user'; } from '@/types/user';
import { getToken } from '@/utils/auth';
import { get, post } from '@/utils/request';
// ==================== 开发环境使用模拟 API ==================== // ==================== 开发环境使用模拟 API ====================
// 取消下面的注释以使用模拟 API 进行开发测试 // 取消下面的注释以使用模拟 API 进行开发测试
// 测试账号:admin/123456, user/123456, guest/123456 // 测试账号:admin/123456, user/123456, guest/123456
import { mockLogin, mockLogout, mockGetUserInfo } from './mock'; import { mockGetUserInfo, mockLogin, mockLogout } from './mock';
import { getToken } from '@/utils/auth';
const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false
...@@ -55,9 +56,12 @@ export const getUserInfo = () => { ...@@ -55,9 +56,12 @@ export const getUserInfo = () => {
* 刷新 Token * 刷新 Token
*/ */
export const refreshToken = (refreshToken: string) => { export const refreshToken = (refreshToken: string) => {
return post<ApiResponse<{ token: string; refreshToken: string }>>('/auth/refresh', { return post<ApiResponse<{ refreshToken: string; token: string }>>(
refreshToken, '/auth/refresh',
}); {
refreshToken,
},
);
}; };
/** /**
...@@ -80,4 +84,3 @@ export const updateUserInfo = (data: UpdateUserInfoParams) => { ...@@ -80,4 +84,3 @@ export const updateUserInfo = (data: UpdateUserInfoParams) => {
export const getCaptcha = () => { export const getCaptcha = () => {
return get<ApiResponse<{ captcha: string; key: string }>>('/auth/captcha'); return get<ApiResponse<{ captcha: string; key: string }>>('/auth/captcha');
}; };
<template> <script setup lang="ts">
<div class="notification-center"> import type { GlobalState } from '../qiankun';
<!-- 通知图标按钮 -->
<div class="notification-badge" @click="togglePanel">
<span class="icon">🔔</span>
<span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
</div>
<!-- 通知面板 -->
<transition name="slide">
<div v-if="showPanel" class="notification-panel">
<div class="panel-header">
<h3>通知中心</h3>
<button v-if="notifications.length > 0" @click="clearAll" class="clear-btn">
清空
</button>
</div>
<div class="notification-list">
<div
v-for="notification in notifications"
:key="notification.id"
:class="['notification-item', `type-${notification.type}`]"
>
<div class="notification-icon">
{{ getIcon(notification.type) }}
</div>
<div class="notification-content">
<div class="notification-title">{{ notification.title }}</div>
<div class="notification-message">{{ notification.message }}</div>
<div class="notification-meta">
<span v-if="notification.from" class="from">来自: {{ notification.from }}</span>
<span class="time">{{ formatTime(notification.timestamp) }}</span>
</div>
</div>
<button @click="removeNotification(notification.id)" class="close-btn">
✕
</button>
</div>
<div v-if="notifications.length === 0" class="empty-state"> import { computed, onMounted, onUnmounted, ref } from 'vue';
<div class="empty-icon">📭</div>
<div class="empty-text">暂无通知</div>
</div>
</div>
</div>
</transition>
</div>
</template>
<script setup lang="ts"> import { communicationManager } from '../qiankun';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { communicationManager, type GlobalState } from '../qiankun';
// 显示面板 // 显示面板
const showPanel = ref(false); const showPanel = ref(false);
...@@ -81,10 +34,10 @@ const getIcon = (type: string) => { ...@@ -81,10 +34,10 @@ const getIcon = (type: string) => {
const formatTime = (timestamp: number) => { const formatTime = (timestamp: number) => {
const now = Date.now(); const now = Date.now();
const diff = now - timestamp; const diff = now - timestamp;
if (diff < 60000) return '刚刚'; if (diff < 60_000) return '刚刚';
if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`; if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}分钟前`;
if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`; if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}小时前`;
return new Date(timestamp).toLocaleString('zh-CN', { return new Date(timestamp).toLocaleString('zh-CN', {
month: '2-digit', month: '2-digit',
day: '2-digit', day: '2-digit',
...@@ -125,6 +78,68 @@ onUnmounted(() => { ...@@ -125,6 +78,68 @@ onUnmounted(() => {
}); });
</script> </script>
<template>
<div class="notification-center">
<!-- 通知图标按钮 -->
<div class="notification-badge" @click="togglePanel">
<span class="icon">🔔</span>
<span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
</div>
<!-- 通知面板 -->
<transition name="slide">
<div v-if="showPanel" class="notification-panel">
<div class="panel-header">
<h3>通知中心</h3>
<button
v-if="notifications.length > 0"
@click="clearAll"
class="clear-btn"
>
清空
</button>
</div>
<div class="notification-list">
<div
v-for="notification in notifications"
:key="notification.id"
class="notification-item"
:class="[`type-${notification.type}`]"
>
<div class="notification-icon">
{{ getIcon(notification.type) }}
</div>
<div class="notification-content">
<div class="notification-title">{{ notification.title }}</div>
<div class="notification-message">{{ notification.message }}</div>
<div class="notification-meta">
<span v-if="notification.from" class="from"
>来自: {{ notification.from }}</span
>
<span class="time">{{
formatTime(notification.timestamp)
}}</span>
</div>
</div>
<button
@click="removeNotification(notification.id)"
class="close-btn"
>
✕
</button>
</div>
<div v-if="notifications.length === 0" class="empty-state">
<div class="empty-icon">📭</div>
<div class="empty-text">暂无通知</div>
</div>
</div>
</div>
</transition>
</div>
</template>
<style scoped> <style scoped>
.notification-center { .notification-center {
position: relative; position: relative;
...@@ -132,18 +147,18 @@ onUnmounted(() => { ...@@ -132,18 +147,18 @@ onUnmounted(() => {
.notification-badge { .notification-badge {
position: relative; position: relative;
width: 40px;
height: 40px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 40px;
height: 40px;
cursor: pointer; cursor: pointer;
border-radius: 50%; border-radius: 50%;
transition: background-color 0.2s; transition: background-color 0.2s;
} }
.notification-badge:hover { .notification-badge:hover {
background-color: rgba(0, 0, 0, 0.05); background-color: rgb(0 0 0 / 5%);
} }
.notification-badge .icon { .notification-badge .icon {
...@@ -154,38 +169,38 @@ onUnmounted(() => { ...@@ -154,38 +169,38 @@ onUnmounted(() => {
position: absolute; position: absolute;
top: 4px; top: 4px;
right: 4px; right: 4px;
display: flex;
align-items: center;
justify-content: center;
min-width: 18px; min-width: 18px;
height: 18px; height: 18px;
padding: 0 4px; padding: 0 4px;
background-color: #ff4d4f;
color: white;
font-size: 12px; font-size: 12px;
color: white;
background-color: #ff4d4f;
border-radius: 9px; border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
} }
.notification-panel { .notification-panel {
position: absolute; position: absolute;
top: 50px; top: 50px;
right: 0; right: 0;
z-index: 1000;
display: flex;
flex-direction: column;
width: 400px; width: 400px;
max-height: 600px; max-height: 600px;
background: white; background: white;
border-radius: 8px; border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); box-shadow: 0 4px 20px rgb(0 0 0 / 15%);
display: flex;
flex-direction: column;
z-index: 1000;
} }
.panel-header { .panel-header {
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
display: flex; display: flex;
justify-content: space-between;
align-items: center; align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
} }
.panel-header h3 { .panel-header h3 {
...@@ -196,11 +211,11 @@ onUnmounted(() => { ...@@ -196,11 +211,11 @@ onUnmounted(() => {
.clear-btn { .clear-btn {
padding: 4px 12px; padding: 4px 12px;
font-size: 14px;
cursor: pointer;
background: transparent; background: transparent;
border: 1px solid #d9d9d9; border: 1px solid #d9d9d9;
border-radius: 4px; border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s; transition: all 0.2s;
} }
...@@ -210,15 +225,15 @@ onUnmounted(() => { ...@@ -210,15 +225,15 @@ onUnmounted(() => {
} }
.notification-list { .notification-list {
overflow-y: auto;
max-height: 500px; max-height: 500px;
overflow-y: auto;
} }
.notification-item { .notification-item {
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
display: flex; display: flex;
gap: 12px; gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
transition: background-color 0.2s; transition: background-color 0.2s;
} }
...@@ -227,8 +242,8 @@ onUnmounted(() => { ...@@ -227,8 +242,8 @@ onUnmounted(() => {
} }
.notification-icon { .notification-icon {
font-size: 24px;
flex-shrink: 0; flex-shrink: 0;
font-size: 24px;
} }
.notification-content { .notification-content {
...@@ -237,17 +252,17 @@ onUnmounted(() => { ...@@ -237,17 +252,17 @@ onUnmounted(() => {
} }
.notification-title { .notification-title {
font-weight: 600;
font-size: 14px;
margin-bottom: 4px; margin-bottom: 4px;
font-size: 14px;
font-weight: 600;
color: #262626; color: #262626;
} }
.notification-message { .notification-message {
font-size: 14px;
color: #595959;
margin-bottom: 8px; margin-bottom: 8px;
font-size: 14px;
line-height: 1.5; line-height: 1.5;
color: #595959;
} }
.notification-meta { .notification-meta {
...@@ -258,21 +273,21 @@ onUnmounted(() => { ...@@ -258,21 +273,21 @@ onUnmounted(() => {
} }
.close-btn { .close-btn {
flex-shrink: 0;
width: 24px; width: 24px;
height: 24px; height: 24px;
flex-shrink: 0;
border: none;
background: transparent;
cursor: pointer;
font-size: 16px; font-size: 16px;
color: #8c8c8c; color: #8c8c8c;
cursor: pointer;
background: transparent;
border: none;
border-radius: 4px; border-radius: 4px;
transition: all 0.2s; transition: all 0.2s;
} }
.close-btn:hover { .close-btn:hover {
background-color: rgba(0, 0, 0, 0.06);
color: #262626; color: #262626;
background-color: rgb(0 0 0 / 6%);
} }
.empty-state { .empty-state {
...@@ -281,13 +296,13 @@ onUnmounted(() => { ...@@ -281,13 +296,13 @@ onUnmounted(() => {
} }
.empty-icon { .empty-icon {
font-size: 48px;
margin-bottom: 12px; margin-bottom: 12px;
font-size: 48px;
} }
.empty-text { .empty-text {
color: #8c8c8c;
font-size: 14px; font-size: 14px;
color: #8c8c8c;
} }
/* 不同类型的通知样式 */ /* 不同类型的通知样式 */
...@@ -323,4 +338,3 @@ onUnmounted(() => { ...@@ -323,4 +338,3 @@ onUnmounted(() => {
transform: translateY(-10px); transform: translateY(-10px);
} }
</style> </style>
<template>
<div class="sidebar-menu-item">
<!-- 菜单项本身 -->
<div
class="menu-item-content"
:class="{
active: isActive,
'has-children': hasChildren,
[`level-${menu.level || 1}`]: true,
}"
@click="handleClick"
>
<!-- 展开/收起图标 -->
<span v-if="hasChildren" class="expand-icon" @click.stop="handleToggle">
{{ isExpanded ? '▼' : '▶' }}
</span>
<!-- 菜单图标 -->
<span v-if="menu.icon" class="menu-icon">{{ menu.icon }}</span>
<!-- 菜单标题 -->
<span class="menu-title">{{ menu.title }}</span>
<!-- 徽章 -->
<span v-if="menu.meta?.badge" class="menu-badge">
{{ menu.meta.badge }}
</span>
</div>
<!-- 子菜单 -->
<transition name="submenu-expand">
<div v-if="hasChildren && isExpanded" class="submenu">
<SidebarMenuItem
v-for="child in menu.children"
:key="child.id"
:menu="child"
:active-path="activePath"
:expanded-keys="expandedKeys"
@click="$emit('click', $event)"
@toggle="$emit('toggle', $event)"
/>
</div>
</transition>
</div>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue';
import type { MenuItem } from '@/types/menu'; import type { MenuItem } from '@/types/menu';
import { computed } from 'vue';
import SidebarMenuItem from './SidebarMenuItem.vue'; import SidebarMenuItem from './SidebarMenuItem.vue';
interface Props { interface Props {
...@@ -73,8 +29,10 @@ const isExpanded = computed(() => { ...@@ -73,8 +29,10 @@ const isExpanded = computed(() => {
// 是否激活(当前路由或子路由激活) // 是否激活(当前路由或子路由激活)
const isActive = computed(() => { const isActive = computed(() => {
return props.activePath === props.menu.path || return (
props.activePath.startsWith(props.menu.path + '/'); props.activePath === props.menu.path ||
props.activePath.startsWith(`${props.menu.path}/`)
);
}); });
// 点击菜单项 // 点击菜单项
...@@ -92,21 +50,67 @@ const handleToggle = () => { ...@@ -92,21 +50,67 @@ const handleToggle = () => {
}; };
</script> </script>
<template>
<div class="sidebar-menu-item">
<!-- 菜单项本身 -->
<div
class="menu-item-content"
:class="{
active: isActive,
'has-children': hasChildren,
[`level-${menu.level || 1}`]: true,
}"
@click="handleClick"
>
<!-- 展开/收起图标 -->
<span v-if="hasChildren" class="expand-icon" @click.stop="handleToggle">
{{ isExpanded ? '▼' : '▶' }}
</span>
<!-- 菜单图标 -->
<span v-if="menu.icon" class="menu-icon">{{ menu.icon }}</span>
<!-- 菜单标题 -->
<span class="menu-title">{{ menu.title }}</span>
<!-- 徽章 -->
<span v-if="menu.meta?.badge" class="menu-badge">
{{ menu.meta.badge }}
</span>
</div>
<!-- 子菜单 -->
<transition name="submenu-expand">
<div v-if="hasChildren && isExpanded" class="submenu">
<SidebarMenuItem
v-for="child in menu.children"
:key="child.id"
:menu="child"
:active-path="activePath"
:expanded-keys="expandedKeys"
@click="$emit('click', $event)"
@toggle="$emit('toggle', $event)"
/>
</div>
</transition>
</div>
</template>
<style scoped> <style scoped>
.sidebar-menu-item { .sidebar-menu-item {
width: 100%; width: 100%;
} }
.menu-item-content { .menu-item-content {
position: relative;
display: flex; display: flex;
align-items: center;
gap: 8px; gap: 8px;
align-items: center;
padding: 10px 16px; padding: 10px 16px;
color: #333; color: #333;
cursor: pointer; cursor: pointer;
transition: all 0.3s;
position: relative;
user-select: none; user-select: none;
transition: all 0.3s;
} }
/* 层级缩进 */ /* 层级缩进 */
...@@ -125,46 +129,46 @@ const handleToggle = () => { ...@@ -125,46 +129,46 @@ const handleToggle = () => {
} }
.menu-item-content:hover { .menu-item-content:hover {
background-color: #f5f5f5;
color: #1890ff; color: #1890ff;
background-color: #f5f5f5;
} }
.menu-item-content.active { .menu-item-content.active {
background-color: #e6f7ff;
color: #1890ff;
font-weight: 500; font-weight: 500;
color: #1890ff;
background-color: #e6f7ff;
} }
.menu-item-content.active::before { .menu-item-content.active::before {
content: '';
position: absolute; position: absolute;
left: 0;
top: 0; top: 0;
bottom: 0; bottom: 0;
left: 0;
width: 3px; width: 3px;
content: '';
background-color: #1890ff; background-color: #1890ff;
} }
.expand-icon { .expand-icon {
flex-shrink: 0;
width: 16px;
height: 16px;
display: flex; display: flex;
flex-shrink: 0;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 16px;
height: 16px;
font-size: 10px; font-size: 10px;
color: #666; color: #666;
transition: transform 0.3s; transition: transform 0.3s;
} }
.menu-icon { .menu-icon {
flex-shrink: 0;
font-size: 16px;
width: 20px;
height: 20px;
display: flex; display: flex;
flex-shrink: 0;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 20px;
height: 20px;
font-size: 16px;
} }
.menu-title { .menu-title {
...@@ -176,15 +180,15 @@ const handleToggle = () => { ...@@ -176,15 +180,15 @@ const handleToggle = () => {
.menu-badge { .menu-badge {
flex-shrink: 0; flex-shrink: 0;
padding: 0 6px; min-width: 18px;
height: 18px; height: 18px;
line-height: 18px; padding: 0 6px;
font-size: 11px; font-size: 11px;
line-height: 18px;
color: #fff; color: #fff;
text-align: center;
background-color: #ff4d4f; background-color: #ff4d4f;
border-radius: 9px; border-radius: 9px;
min-width: 18px;
text-align: center;
} }
.submenu { .submenu {
...@@ -199,15 +203,15 @@ const handleToggle = () => { ...@@ -199,15 +203,15 @@ const handleToggle = () => {
.submenu-expand-enter-from, .submenu-expand-enter-from,
.submenu-expand-leave-to { .submenu-expand-leave-to {
opacity: 0;
max-height: 0; max-height: 0;
opacity: 0;
transform: translateY(-10px); transform: translateY(-10px);
} }
.submenu-expand-enter-to, .submenu-expand-enter-to,
.submenu-expand-leave-from { .submenu-expand-leave-from {
opacity: 1;
max-height: 1000px; max-height: 1000px;
opacity: 1;
transform: translateY(0); transform: translateY(0);
} }
...@@ -218,7 +222,7 @@ const handleToggle = () => { ...@@ -218,7 +222,7 @@ const handleToggle = () => {
/* 二级菜单样式 */ /* 二级菜单样式 */
.level-2 .menu-item-content { .level-2 .menu-item-content {
background-color: rgba(0, 0, 0, 0.02); background-color: rgb(0 0 0 / 2%);
} }
.level-2 .menu-item-content:hover { .level-2 .menu-item-content:hover {
...@@ -227,11 +231,10 @@ const handleToggle = () => { ...@@ -227,11 +231,10 @@ const handleToggle = () => {
/* 三级菜单样式 */ /* 三级菜单样式 */
.level-3 .menu-item-content { .level-3 .menu-item-content {
background-color: rgba(0, 0, 0, 0.04); background-color: rgb(0 0 0 / 4%);
} }
.level-3 .menu-item-content:hover { .level-3 .menu-item-content:hover {
background-color: #ebebeb; background-color: #ebebeb;
} }
</style> </style>
...@@ -13,7 +13,7 @@ export const homeMenus: MenuItem[] = [ ...@@ -13,7 +13,7 @@ export const homeMenus: MenuItem[] = [
path: '/home/dashboard', path: '/home/dashboard',
icon: '📊', icon: '📊',
level: 1, level: 1,
} },
]; ];
// Vue 微应用侧边栏菜单(多级示例) // Vue 微应用侧边栏菜单(多级示例)
...@@ -49,16 +49,15 @@ export const vueAppMenus: MenuItem[] = [ ...@@ -49,16 +49,15 @@ export const vueAppMenus: MenuItem[] = [
path: '/subapp-vue/user', path: '/subapp-vue/user',
icon: '🎯', icon: '🎯',
level: 1, level: 1,
children: [ children: [],
], },
},{ {
id: 'marketing', id: 'marketing',
title: '系统管理', title: '系统管理',
path: '/subapp-vue/settings', path: '/subapp-vue/settings',
icon: '🎯', icon: '🎯',
level: 1, level: 1,
children: [ children: [],
],
}, },
]; ];
...@@ -166,7 +165,7 @@ export const topMenus: TopMenuItem[] = [ ...@@ -166,7 +165,7 @@ export const topMenus: TopMenuItem[] = [
* 根据路径获取对应的侧边栏菜单 * 根据路径获取对应的侧边栏菜单
*/ */
export function getSidebarMenusByPath(path: string): MenuItem[] { export function getSidebarMenusByPath(path: string): MenuItem[] {
const topMenu = topMenus.find(menu => path.startsWith(menu.path)); const topMenu = topMenus.find((menu) => path.startsWith(menu.path));
return topMenu?.sidebarMenus || []; return topMenu?.sidebarMenus || [];
} }
...@@ -189,26 +188,32 @@ export function findMenuItem(menus: MenuItem[], id: string): MenuItem | null { ...@@ -189,26 +188,32 @@ export function findMenuItem(menus: MenuItem[], id: string): MenuItem | null {
/** /**
* 获取菜单的所有父级路径 * 获取菜单的所有父级路径
*/ */
export function getMenuParentPaths(menus: MenuItem[], targetPath: string): string[] { export function getMenuParentPaths(
menus: MenuItem[],
targetPath: string,
): string[] {
const paths: string[] = []; const paths: string[] = [];
function findPath(items: MenuItem[], target: string, currentPaths: string[]): boolean { function findPath(
items: MenuItem[],
target: string,
currentPaths: string[],
): boolean {
for (const item of items) { for (const item of items) {
const newPaths = [...currentPaths, item.path]; const newPaths = [...currentPaths, item.path];
if (item.path === target) { if (item.path === target) {
paths.push(...newPaths); paths.push(...newPaths);
return true; return true;
} }
if (item.children && findPath(item.children, target, newPaths)) { if (item.children && findPath(item.children, target, newPaths)) {
return true; return true;
} }
} }
return false; return false;
} }
findPath(menus, targetPath, []); findPath(menus, targetPath, []);
return paths; return paths;
} }
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 router from './router';
import { setupQiankun } from './qiankun'; import { setupQiankun } from './qiankun';
import { useUserStore, useAppStore } from './stores'; import router from './router';
import { useAppStore, useUserStore } from './stores';
import { getToken } from './utils/auth'; import { getToken } from './utils/auth';
import './style.css'; import './style.css';
// 创建应用实例 // 创建应用实例
...@@ -31,12 +34,12 @@ async function initApp() { ...@@ -31,12 +34,12 @@ async function initApp() {
if (token) { if (token) {
const userStore = useUserStore(); const userStore = useUserStore();
userStore.setTokenValue(token); userStore.setTokenValue(token);
// 尝试获取用户信息(如果失败,路由守卫会处理) // 尝试获取用户信息(如果失败,路由守卫会处理)
try { try {
await userStore.getUserInfo(); await userStore.getUserInfo();
console.log('[基座] 用户信息恢复成功,已同步到 qiankun 全局状态'); console.log('[基座] 用户信息恢复成功,已同步到 qiankun 全局状态');
} catch (error) { } catch {
console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录'); console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
} }
} }
...@@ -51,14 +54,14 @@ async function initApp() { ...@@ -51,14 +54,14 @@ async function initApp() {
function setupStoreSync() { function setupStoreSync() {
const userStore = useUserStore(); const userStore = useUserStore();
const appStore = useAppStore(); const appStore = useAppStore();
// 监听用户信息变化 // 监听用户信息变化
userStore.$subscribe(() => { userStore.$subscribe(() => {
console.log('[基座] 用户 Store 变化,同步到 qiankun 全局状态'); console.log('[基座] 用户 Store 变化,同步到 qiankun 全局状态');
// 每次 Store 变化时,同步用户信息 // 每次 Store 变化时,同步用户信息
userStore.syncUserToQiankun(); userStore.syncUserToQiankun();
}); });
// 监听主题变化,同步到 qiankun 全局状态 // 监听主题变化,同步到 qiankun 全局状态
appStore.$subscribe((_mutation, state) => { appStore.$subscribe((_mutation, state) => {
import('./qiankun/communication').then(({ communicationManager }) => { import('./qiankun/communication').then(({ communicationManager }) => {
...@@ -85,4 +88,3 @@ initApp().then(() => { ...@@ -85,4 +88,3 @@ initApp().then(() => {
setupQiankun(); setupQiankun();
}); });
}); });
...@@ -32,18 +32,18 @@ export const microApps: MicroAppConfig[] = [ ...@@ -32,18 +32,18 @@ export const microApps: MicroAppConfig[] = [
*/ */
function getAppEntry(appName: string, defaultEntry: string): string { function getAppEntry(appName: string, defaultEntry: string): string {
const env = (import.meta as any).env?.MODE || 'development'; const env = (import.meta as any).env?.MODE || 'development';
// 开发环境使用默认地址 // 开发环境使用默认地址
if (env === 'development') { if (env === 'development') {
return defaultEntry; return defaultEntry;
} }
// 优先使用环境变量配置的基础地址 // 优先使用环境变量配置的基础地址
const baseUrl = (import.meta as any).env?.VITE_MICRO_APP_BASE_URL; const baseUrl = (import.meta as any).env?.VITE_MICRO_APP_BASE_URL;
if (baseUrl) { if (baseUrl) {
return `${baseUrl}/${appName}`; return `${baseUrl}/${appName}`;
} }
// 如果未配置环境变量,使用当前域名的相对路径(同域部署) // 如果未配置环境变量,使用当前域名的相对路径(同域部署)
// 例如:https://your-domain.com/subapp-vue // 例如:https://your-domain.com/subapp-vue
return `${window.location.origin}/${appName}`; return `${window.location.origin}/${appName}`;
...@@ -84,4 +84,3 @@ export function getMicroAppByPath(path: string): MicroAppConfig | undefined { ...@@ -84,4 +84,3 @@ export function getMicroAppByPath(path: string): MicroAppConfig | undefined {
export function isMicroAppRegistered(name: string): boolean { export function isMicroAppRegistered(name: string): boolean {
return microApps.some((app) => app.name === name); return microApps.some((app) => app.name === name);
} }
...@@ -6,23 +6,23 @@ import { initGlobalState, MicroAppStateActions } from 'qiankun'; ...@@ -6,23 +6,23 @@ import { initGlobalState, MicroAppStateActions } from 'qiankun';
*/ */
export interface GlobalState { export interface GlobalState {
// 用户信息 // 用户信息
user: { user: null | {
avatar: string;
id: string; id: string;
name: string; name: string;
avatar: string;
role: string;
permissions: string[]; permissions: string[];
} | null; role: string;
};
// 主题配置 // 主题配置
theme: { theme: {
mode: 'light' | 'dark'; mode: 'dark' | 'light';
primaryColor: string; primaryColor: string;
}; };
// 消息通知列表 // 消息通知列表
notifications: Notification[]; notifications: Notification[];
// 系统配置 // 系统配置
config: { config: {
apiBaseUrl: string; apiBaseUrl: string;
...@@ -30,14 +30,14 @@ export interface GlobalState { ...@@ -30,14 +30,14 @@ export interface GlobalState {
}; };
// 当前激活的菜单信息 // 当前激活的菜单信息
currentMenu: { currentMenu: null | {
menuId: string;
menuTitle: string;
menuPath: string;
menuIcon?: string; menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>; menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
timestamp: number; timestamp: number;
} | null; };
} }
/** /**
...@@ -45,7 +45,7 @@ export interface GlobalState { ...@@ -45,7 +45,7 @@ export interface GlobalState {
*/ */
export interface Notification { export interface Notification {
id: string; id: string;
type: 'success' | 'warning' | 'error' | 'info'; type: 'error' | 'info' | 'success' | 'warning';
title: string; title: string;
message: string; message: string;
timestamp: number; timestamp: number;
...@@ -82,34 +82,37 @@ const initialState: GlobalState = { ...@@ -82,34 +82,37 @@ const initialState: GlobalState = {
class CommunicationManager { class CommunicationManager {
// qiankun 的状态管理实例 // qiankun 的状态管理实例
private actions: MicroAppStateActions | null = null; private actions: MicroAppStateActions | null = null;
// 当前全局状态的本地副本(qiankun 不提供 getGlobalState 方法,需要自己维护) // 当前全局状态的本地副本(qiankun 不提供 getGlobalState 方法,需要自己维护)
private currentState: GlobalState = initialState; private currentState: GlobalState = initialState;
// 状态变化监听器列表 // 状态变化监听器列表
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> = []; private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[];
/** /**
* 初始化全局状态 * 添加通知消息
* @param notification 通知消息(不含id和timestamp)
*/ */
init() { addNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
// 初始化 qiankun 的全局状态 const newNotification: Notification = {
this.actions = initGlobalState(initialState); ...notification,
id: Date.now().toString(),
// 监听状态变化,同步更新本地副本 timestamp: Date.now(),
this.actions.onGlobalStateChange((state, prev) => { };
console.log('[基座通信] 全局状态变化:', state, prev);
this.setGlobalState({
// 更新本地状态副本 notifications: [...this.currentState.notifications, newNotification],
this.currentState = state as GlobalState; });
}
// 触发所有监听器
this.listeners.forEach(listener => { /**
listener(state as GlobalState, prev as GlobalState); * 清空所有通知
}); */
clearNotifications() {
this.setGlobalState({
notifications: [],
}); });
console.log('[基座通信] 通信管理器初始化完成');
} }
/** /**
...@@ -121,44 +124,26 @@ class CommunicationManager { ...@@ -121,44 +124,26 @@ class CommunicationManager {
} }
/** /**
* 设置全局状态(支持部分更新) * 初始化全局状态
* @param state 要更新的状态
*/ */
setGlobalState(state: Partial<GlobalState>) { init() {
if (this.actions) { // 初始化 qiankun 的全局状态
// 深度合并更新本地状态副本(立即更新,避免异步延迟) this.actions = initGlobalState(initialState);
this.currentState = this.deepMerge(this.currentState, state);
// 同步到 qiankun 全局状态(只传入变化的部分)
this.actions.setGlobalState(state);
console.log('[基座通信] 全局状态已更新:', state);
} else {
console.warn('[基座通信] 通信管理器未初始化');
}
}
/** // 监听状态变化,同步更新本地副本
* 深度合并对象(简单实现) this.actions.onGlobalStateChange((state, prev) => {
*/ console.log('[基座通信] 全局状态变化:', state, prev);
private deepMerge(target: any, source: any): any {
const result = { ...target }; // 更新本地状态副本
this.currentState = state as GlobalState;
for (const key in source) {
const sourceValue = source[key]; // 触发所有监听器
const targetValue = target[key]; this.listeners.forEach((listener) => {
listener(state as GlobalState, prev as GlobalState);
if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) { });
if (targetValue && typeof targetValue === 'object' && !Array.isArray(targetValue)) { });
result[key] = this.deepMerge(targetValue, sourceValue);
} else { console.log('[基座通信] 通信管理器初始化完成');
result[key] = sourceValue;
}
} else {
result[key] = sourceValue;
}
}
return result;
} }
/** /**
...@@ -166,72 +151,45 @@ class CommunicationManager { ...@@ -166,72 +151,45 @@ class CommunicationManager {
* @param callback 回调函数 * @param callback 回调函数
* @returns 取消监听的函数 * @returns 取消监听的函数
*/ */
onStateChange(callback: (state: GlobalState, prev: GlobalState) => void): () => void { onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback); this.listeners.push(callback);
// 返回取消监听的函数 // 返回取消监听的函数
return () => { return () => {
const index = this.listeners.indexOf(callback); const index = this.listeners.indexOf(callback);
if (index > -1) { if (index !== -1) {
this.listeners.splice(index, 1); this.listeners.splice(index, 1);
} }
}; };
} }
/** /**
* 更新用户信息
* @param user 用户信息
*/
updateUser(user: GlobalState['user']) {
this.setGlobalState({ user });
}
/**
* 更新主题
* @param theme 主题配置
*/
updateTheme(theme: Partial<GlobalState['theme']>) {
this.setGlobalState({
theme: {
...this.currentState.theme,
...theme,
} as GlobalState['theme'],
});
}
/**
* 添加通知消息
* @param notification 通知消息(不含id和timestamp)
*/
addNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
};
this.setGlobalState({
notifications: [...this.currentState.notifications, newNotification],
});
}
/**
* 移除通知消息 * 移除通知消息
* @param id 通知ID * @param id 通知ID
*/ */
removeNotification(id: string) { removeNotification(id: string) {
this.setGlobalState({ this.setGlobalState({
notifications: this.currentState.notifications.filter(n => n.id !== id), notifications: this.currentState.notifications.filter((n) => n.id !== id),
}); });
} }
/** /**
* 清空所有通知 * 设置全局状态(支持部分更新)
* @param state 要更新的状态
*/ */
clearNotifications() { setGlobalState(state: Partial<GlobalState>) {
this.setGlobalState({ if (this.actions) {
notifications: [], // 深度合并更新本地状态副本(立即更新,避免异步延迟)
}); this.currentState = this.deepMerge(this.currentState, state);
// 同步到 qiankun 全局状态(只传入变化的部分)
this.actions.setGlobalState(state);
console.log('[基座通信] 全局状态已更新:', state);
} else {
console.warn('[基座通信] 通信管理器未初始化');
}
} }
/** /**
...@@ -252,11 +210,11 @@ class CommunicationManager { ...@@ -252,11 +210,11 @@ class CommunicationManager {
* @param menu 菜单信息 * @param menu 菜单信息
*/ */
updateCurrentMenu(menu: { updateCurrentMenu(menu: {
menuId: string;
menuTitle: string;
menuPath: string;
menuIcon?: string; menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>; menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
}) { }) {
this.setGlobalState({ this.setGlobalState({
currentMenu: { currentMenu: {
...@@ -266,6 +224,56 @@ class CommunicationManager { ...@@ -266,6 +224,56 @@ class CommunicationManager {
}); });
console.log('[基座通信] 当前菜单已更新:', menu); console.log('[基座通信] 当前菜单已更新:', menu);
} }
/**
* 更新主题
* @param theme 主题配置
*/
updateTheme(theme: Partial<GlobalState['theme']>) {
this.setGlobalState({
theme: {
...this.currentState.theme,
...theme,
} as GlobalState['theme'],
});
}
/**
* 更新用户信息
* @param user 用户信息
*/
updateUser(user: GlobalState['user']) {
this.setGlobalState({ user });
}
/**
* 深度合并对象(简单实现)
*/
private deepMerge(target: any, source: any): any {
const result = { ...target };
for (const key in source) {
const sourceValue = source[key];
const targetValue = target[key];
if (
sourceValue &&
typeof sourceValue === 'object' &&
!Array.isArray(sourceValue)
) {
result[key] =
targetValue &&
typeof targetValue === 'object' &&
!Array.isArray(targetValue)
? this.deepMerge(targetValue, sourceValue)
: sourceValue;
} else {
result[key] = sourceValue;
}
}
return result;
}
} }
// 导出单例 // 导出单例
...@@ -280,7 +288,7 @@ export const communicationManager = new CommunicationManager(); ...@@ -280,7 +288,7 @@ export const communicationManager = new CommunicationManager();
export function broadcast( export function broadcast(
type: Notification['type'], type: Notification['type'],
title: string, title: string,
message: string message: string,
) { ) {
communicationManager.addNotification({ communicationManager.addNotification({
type, type,
...@@ -289,4 +297,3 @@ export function broadcast( ...@@ -289,4 +297,3 @@ export function broadcast(
from: '基座应用', from: '基座应用',
}); });
} }
<template>
<div class="micro-app-container">
<!-- 微应用加载状态显示 -->
<!-- <div v-if="loading" class="loading-container">
<div class="loading-spinner"></div>
<p class="loading-text">正在加载微应用...</p>
</div>
-->
<!-- 微应用加载失败提示 -->
<div v-if="error" class="error-container">
<div class="error-icon">⚠️</div>
<p class="error-text">{{ error }}</p>
<button class="retry-button" @click="handleRetry">重试</button>
</div>
</div>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'; import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { getMicroAppByPath } from '../apps'; import { getMicroAppByPath } from '../apps';
const route = useRoute(); const route = useRoute();
const loading = ref(true); const loading = ref(true);
const error = ref(''); const error = ref('');
let timer: number | null = null; let timer: null | number = null;
/** /**
* 初始化微应用容器 * 初始化微应用容器
...@@ -32,7 +16,7 @@ let timer: number | null = null; ...@@ -32,7 +16,7 @@ let timer: number | null = null;
onMounted(() => { onMounted(() => {
// 获取当前路径对应的微应用 // 获取当前路径对应的微应用
const microApp = getMicroAppByPath(route.path); const microApp = getMicroAppByPath(route.path);
if (!microApp) { if (!microApp) {
error.value = '未找到对应的微应用配置'; error.value = '未找到对应的微应用配置';
loading.value = false; loading.value = false;
...@@ -42,7 +26,7 @@ onMounted(() => { ...@@ -42,7 +26,7 @@ onMounted(() => {
// 模拟加载延迟和错误处理 // 模拟加载延迟和错误处理
timer = window.setTimeout(() => { timer = window.setTimeout(() => {
loading.value = false; loading.value = false;
// 这里可以添加更多的加载逻辑 // 这里可以添加更多的加载逻辑
console.log('[MicroAppContainer] 微应用容器已准备就绪:', microApp.name); console.log('[MicroAppContainer] 微应用容器已准备就绪:', microApp.name);
}, 1000); }, 1000);
...@@ -64,14 +48,41 @@ onUnmounted(() => { ...@@ -64,14 +48,41 @@ onUnmounted(() => {
const handleRetry = () => { const handleRetry = () => {
error.value = ''; error.value = '';
loading.value = true; loading.value = true;
timer = window.setTimeout(() => { timer = window.setTimeout(() => {
loading.value = false; loading.value = false;
}, 1000); }, 1000);
}; };
</script> </script>
<template>
<div class="micro-app-container">
<!-- 微应用加载状态显示 -->
<!-- <div v-if="loading" class="loading-container">
<div class="loading-spinner"></div>
<p class="loading-text">正在加载微应用...</p>
</div>
-->
<!-- 微应用加载失败提示 -->
<div v-if="error" class="error-container">
<div class="error-icon">⚠️</div>
<p class="error-text">{{ error }}</p>
<button class="retry-button" @click="handleRetry">重试</button>
</div>
</div>
</template>
<style scoped> <style scoped>
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.micro-app-container { .micro-app-container {
width: 100%; width: 100%;
} }
...@@ -92,19 +103,10 @@ const handleRetry = () => { ...@@ -92,19 +103,10 @@ const handleRetry = () => {
animation: spin 1s linear infinite; animation: spin 1s linear infinite;
} }
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loading-text { .loading-text {
margin-top: 16px; margin-top: 16px;
color: #666;
font-size: 14px; font-size: 14px;
color: #666;
} }
/* 错误状态 */ /* 错误状态 */
...@@ -117,24 +119,24 @@ const handleRetry = () => { ...@@ -117,24 +119,24 @@ const handleRetry = () => {
} }
.error-icon { .error-icon {
font-size: 48px;
margin-bottom: 16px; margin-bottom: 16px;
font-size: 48px;
} }
.error-text { .error-text {
color: #ff4d4f;
font-size: 14px;
margin-bottom: 16px; margin-bottom: 16px;
font-size: 14px;
color: #ff4d4f;
} }
.retry-button { .retry-button {
padding: 8px 24px; padding: 8px 24px;
background-color: #1890ff; font-size: 14px;
color: white; color: white;
cursor: pointer;
background-color: #1890ff;
border: none; border: none;
border-radius: 4px; border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s; transition: background-color 0.3s;
} }
...@@ -146,4 +148,3 @@ const handleRetry = () => { ...@@ -146,4 +148,3 @@ const handleRetry = () => {
background-color: #096dd9; background-color: #096dd9;
} }
</style> </style>
import { registerMicroApps, start, addGlobalUncaughtErrorHandler } from 'qiankun'; import {
addGlobalUncaughtErrorHandler,
registerMicroApps,
start,
} from 'qiankun';
import { microApps } from './apps'; import { microApps } from './apps';
import { microAppLifecycles } from './lifecycles';
import { communicationManager } from './communication'; import { communicationManager } from './communication';
import { microAppLifecycles } from './lifecycles';
/** /**
* qiankun 配置选项 * qiankun 配置选项
...@@ -10,7 +15,7 @@ const qiankunConfig = { ...@@ -10,7 +15,7 @@ const qiankunConfig = {
// 预加载策略:改为 false,避免在容器未就绪时预加载导致的问题 // 预加载策略:改为 false,避免在容器未就绪时预加载导致的问题
// 刷新页面时,先让当前路由的微应用正常加载,再进行预加载 // 刷新页面时,先让当前路由的微应用正常加载,再进行预加载
prefetch: false, prefetch: false,
// 沙箱配置 // 沙箱配置
sandbox: { sandbox: {
// 是否开启严格样式隔离(Shadow DOM) // 是否开启严格样式隔离(Shadow DOM)
...@@ -18,13 +23,13 @@ const qiankunConfig = { ...@@ -18,13 +23,13 @@ const qiankunConfig = {
// 是否开启实验性样式隔离(scoped css) // 是否开启实验性样式隔离(scoped css)
experimentalStyleIsolation: true, experimentalStyleIsolation: true,
}, },
// 单例模式:同一时间只能有一个微应用在运行 // 单例模式:同一时间只能有一个微应用在运行
singular: true, singular: true,
// 获取公共资源的方式 // 获取公共资源的方式
// fetch: customFetch, // fetch: customFetch,
// 在第一个微应用加载后再开启预加载 // 在第一个微应用加载后再开启预加载
// 这样可以避免刷新时的竞态条件 // 这样可以避免刷新时的竞态条件
}; };
...@@ -37,13 +42,12 @@ export function setupQiankun() { ...@@ -37,13 +42,12 @@ export function setupQiankun() {
communicationManager.init(); communicationManager.init();
// 2. 注册微应用 // 2. 注册微应用
console.log("注册qiankun传参:microApps",microApps); console.log('注册qiankun传参:microApps', microApps);
console.log("注册qiankun钩子:",microAppLifecycles); console.log('注册qiankun钩子:', microAppLifecycles);
registerMicroApps(microApps, microAppLifecycles); registerMicroApps(microApps, microAppLifecycles);
// 3. 添加全局错误处理 // 3. 添加全局错误处理
addGlobalUncaughtErrorHandler((event) => { addGlobalUncaughtErrorHandler((event) => {
// 可以在这里做一些全局错误处理 // 可以在这里做一些全局错误处理
// 例如:错误上报、错误提示等 // 例如:错误上报、错误提示等
const { message } = event as any; const { message } = event as any;
...@@ -59,10 +63,15 @@ export function setupQiankun() { ...@@ -59,10 +63,15 @@ export function setupQiankun() {
/** /**
* 导出相关模块,方便外部使用 * 导出相关模块,方便外部使用
*/ */
export { microApps, getMicroAppConfig, getMicroAppNames, getMicroAppByPath, isMicroAppRegistered } from './apps'; export {
getMicroAppByPath,
getMicroAppConfig,
getMicroAppNames,
isMicroAppRegistered,
microApps,
} from './apps';
export { broadcast, communicationManager } from './communication';
export type { GlobalState, Notification } from './communication';
export { microAppLifecycles } from './lifecycles'; export { microAppLifecycles } from './lifecycles';
export { communicationManager, broadcast } from './communication';
export * from './types'; export * from './types';
export * from './utils'; export * from './utils';
export type { GlobalState, Notification } from './communication';
...@@ -9,11 +9,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -9,11 +9,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/ */
beforeLoad: async (app) => { beforeLoad: async (app) => {
console.log('[qiankun] before load', app.name); console.log('[qiankun] before load', app.name);
// 可以在这里做一些加载前的准备工作 // 可以在这里做一些加载前的准备工作
// 例如:显示加载动画、设置全局状态等 // 例如:显示加载动画、设置全局状态等
return Promise.resolve();
}, },
/** /**
...@@ -21,12 +19,12 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -21,12 +19,12 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/ */
beforeMount: async (app) => { beforeMount: async (app) => {
console.log('[qiankun] before mount', app.name); console.log('[qiankun] before mount', app.name);
// 确保主应用的数据已准备好并同步到全局状态 // 确保主应用的数据已准备好并同步到全局状态
try { try {
const { communicationManager } = await import('./communication'); const { communicationManager } = await import('./communication');
const globalState = communicationManager.getGlobalState(); const globalState = communicationManager.getGlobalState();
// 如果用户信息为空,尝试从 Store 获取并同步 // 如果用户信息为空,尝试从 Store 获取并同步
if (!globalState.user) { if (!globalState.user) {
const { useUserStore } = await import('@/stores'); const { useUserStore } = await import('@/stores');
...@@ -38,8 +36,6 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -38,8 +36,6 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
} catch (error) { } catch (error) {
console.warn('[qiankun] 同步用户信息失败:', error); console.warn('[qiankun] 同步用户信息失败:', error);
} }
return Promise.resolve();
}, },
/** /**
...@@ -47,11 +43,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -47,11 +43,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/ */
afterMount: async (app) => { afterMount: async (app) => {
console.log('[qiankun] after mount', app.name); console.log('[qiankun] after mount', app.name);
// 可以在这里做一些挂载后的处理 // 可以在这里做一些挂载后的处理
// 例如:隐藏加载动画、记录日志、埋点统计等 // 例如:隐藏加载动画、记录日志、埋点统计等
return Promise.resolve();
}, },
/** /**
...@@ -59,11 +53,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -59,11 +53,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/ */
beforeUnmount: async (app) => { beforeUnmount: async (app) => {
console.log('[qiankun] before unmount', app.name); console.log('[qiankun] before unmount', app.name);
// 可以在这里做一些卸载前的清理工作 // 可以在这里做一些卸载前的清理工作
// 例如:保存状态、显示卸载动画等 // 例如:保存状态、显示卸载动画等
return Promise.resolve();
}, },
/** /**
...@@ -71,11 +63,8 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -71,11 +63,8 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/ */
afterUnmount: async (app) => { afterUnmount: async (app) => {
console.log('[qiankun] after unmount', app.name); console.log('[qiankun] after unmount', app.name);
// 可以在这里做一些卸载后的清理工作 // 可以在这里做一些卸载后的清理工作
// 例如:清除缓存、重置状态、移除事件监听等 // 例如:清除缓存、重置状态、移除事件监听等
return Promise.resolve();
}, },
}; };
import type { FrameworkLifeCycles } from 'qiankun';
/** /**
* 微应用配置类型 * 微应用配置类型
*/ */
...@@ -7,7 +5,7 @@ export interface MicroAppConfig { ...@@ -7,7 +5,7 @@ export interface MicroAppConfig {
name: string; name: string;
entry: string; entry: string;
container: string; container: string;
activeRule: string | string[] | ((location: Location) => boolean); activeRule: ((location: Location) => boolean) | string | string[];
props?: Record<string, any>; props?: Record<string, any>;
loader?: (loading: boolean) => void; loader?: (loading: boolean) => void;
} }
...@@ -21,17 +19,17 @@ export type MicroAppEnv = 'development' | 'production' | 'test'; ...@@ -21,17 +19,17 @@ export type MicroAppEnv = 'development' | 'production' | 'test';
* 微应用状态 * 微应用状态
*/ */
export enum MicroAppStatus { export enum MicroAppStatus {
NOT_LOADED = 'NOT_LOADED',
LOADING = 'LOADING',
LOADED = 'LOADED', LOADED = 'LOADED',
MOUNTING = 'MOUNTING', LOADING = 'LOADING',
MOUNTED = 'MOUNTED', MOUNTED = 'MOUNTED',
UNMOUNTING = 'UNMOUNTING', MOUNTING = 'MOUNTING',
NOT_LOADED = 'NOT_LOADED',
UNMOUNTED = 'UNMOUNTED', UNMOUNTED = 'UNMOUNTED',
UNMOUNTING = 'UNMOUNTING',
} }
/** /**
* qiankun 生命周期钩子类型 * qiankun 生命周期钩子类型
*/ */
export type { FrameworkLifeCycles };
export { type FrameworkLifeCycles } from 'qiankun';
...@@ -73,8 +73,8 @@ export function formatMicroAppPath(path: string, base: string = ''): string { ...@@ -73,8 +73,8 @@ export function formatMicroAppPath(path: string, base: string = ''): string {
* @param currentPath 当前路径 * @param currentPath 当前路径
*/ */
export function isMicroAppActive( export function isMicroAppActive(
activeRule: string | ((location: Location) => boolean), activeRule: ((location: Location) => boolean) | string,
currentPath: string = window.location.pathname currentPath: string = window.location.pathname,
): boolean { ): boolean {
if (typeof activeRule === 'function') { if (typeof activeRule === 'function') {
return activeRule(window.location); return activeRule(window.location);
...@@ -115,9 +115,9 @@ export function prefetchMicroApp(entry: string): Promise<void> { ...@@ -115,9 +115,9 @@ export function prefetchMicroApp(entry: string): Promise<void> {
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'prefetch'; link.rel = 'prefetch';
link.href = entry; link.href = entry;
link.onload = () => resolve(); link.addEventListener('load', () => resolve());
link.onerror = () => reject(new Error(`预加载失败: ${entry}`)); link.onerror = () => reject(new Error(`预加载失败: ${entry}`));
document.head.appendChild(link); document.head.append(link);
}); });
} }
...@@ -135,4 +135,3 @@ export function getMicroAppPerformance() { ...@@ -135,4 +135,3 @@ export function getMicroAppPerformance() {
} }
return null; return null;
} }
import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores'; import { useUserStore } from '@/stores';
import { getToken } from '@/utils/auth'; import { getToken } from '@/utils/auth';
...@@ -110,18 +112,16 @@ const router = createRouter({ ...@@ -110,18 +112,16 @@ const router = createRouter({
}); });
// 白名单:不需要登录的路由 // 白名单:不需要登录的路由
const whiteList = ['/login', '/register', '/forgot-password']; const whiteList = new Set(['/forgot-password', '/login', '/register']);
/** /**
* 全局前置守卫 * 全局前置守卫
*/ */
router.beforeEach(async (to, _from, next) => { router.beforeEach(async (to, _from, next) => {
// 设置页面标题 // 设置页面标题
if (to.meta.title) { document.title = to.meta.title
document.title = `${to.meta.title} - SCRM 微前端`; ? `${to.meta.title} - SCRM 微前端`
} else { : 'SCRM 微前端平台';
document.title = 'SCRM 微前端平台';
}
// 获取 token // 获取 token
const token = getToken(); const token = getToken();
...@@ -137,27 +137,7 @@ router.beforeEach(async (to, _from, next) => { ...@@ -137,27 +137,7 @@ router.beforeEach(async (to, _from, next) => {
next({ path: '/home' }); next({ path: '/home' });
} else { } else {
// 检查是否已获取用户信息 // 检查是否已获取用户信息
if (!userStore.userInfo) { if (userStore.userInfo) {
try {
// 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo();
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} catch (error) {
// 获取用户信息失败,清除 token 并跳转到登录页
console.error('获取用户信息失败:', error);
await userStore.logout();
next({
path: '/login',
query: { redirect: to.fullPath },
});
}
} else {
// 检查权限 // 检查权限
if (to.meta.permissions || to.meta.roles) { if (to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore); const hasPermission = checkPermission(to, userStore);
...@@ -179,22 +159,42 @@ router.beforeEach(async (to, _from, next) => { ...@@ -179,22 +159,42 @@ router.beforeEach(async (to, _from, next) => {
} }
next(); next();
} }
} else {
try {
// 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo();
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} catch (error) {
// 获取用户信息失败,清除 token 并跳转到登录页
console.error('获取用户信息失败:', error);
await userStore.logout();
next({
path: '/login',
query: { redirect: to.fullPath },
});
}
} }
} }
} else { } else {
// 未登录 // 未登录
if (whiteList.includes(to.path)) { if (whiteList.has(to.path)) {
// 在白名单中,直接放行 // 在白名单中,直接放行
next(); next();
} else if (!requiresAuth) { } else if (requiresAuth) {
// 不需要认证的页面,直接放行
next();
} else {
// 需要认证但未登录,跳转到登录页 // 需要认证但未登录,跳转到登录页
next({ next({
path: '/login', path: '/login',
query: { redirect: to.fullPath }, query: { redirect: to.fullPath },
}); });
} else {
// 不需要认证的页面,直接放行
next();
} }
} }
}); });
...@@ -214,19 +214,19 @@ router.afterEach((to, from) => { ...@@ -214,19 +214,19 @@ router.afterEach((to, from) => {
async function syncDataToQiankun(userStore: any): Promise<void> { async function syncDataToQiankun(userStore: any): Promise<void> {
try { try {
console.log('[路由守卫] 准备进入微应用,同步数据到 qiankun 全局状态'); console.log('[路由守卫] 准备进入微应用,同步数据到 qiankun 全局状态');
// 同步用户信息 // 同步用户信息
if (userStore.userInfo) { if (userStore.userInfo) {
userStore.syncUserToQiankun(); userStore.syncUserToQiankun();
} }
// 延迟导入 qiankun 通信模块 // 延迟导入 qiankun 通信模块
const { communicationManager } = await import('@/qiankun/communication'); const { communicationManager } = await import('@/qiankun/communication');
// 获取当前全局状态,确认数据已同步 // 获取当前全局状态,确认数据已同步
const globalState = communicationManager.getGlobalState(); const globalState = communicationManager.getGlobalState();
console.log('[路由守卫] 当前全局状态:', globalState); console.log('[路由守卫] 当前全局状态:', globalState);
// 如果用户信息还未同步,强制同步一次 // 如果用户信息还未同步,强制同步一次
if (!globalState.user && userStore.userInfo) { if (!globalState.user && userStore.userInfo) {
console.log('[路由守卫] 检测到用户信息未同步,强制同步'); console.log('[路由守卫] 检测到用户信息未同步,强制同步');
...@@ -267,4 +267,3 @@ function checkPermission(route: any, userStore: any): boolean { ...@@ -267,4 +267,3 @@ function checkPermission(route: any, userStore: any): boolean {
} }
export default router; export default router;
import { computed, ref } from 'vue';
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
/** /**
* 应用全局状态管理 * 应用全局状态管理
...@@ -7,16 +8,16 @@ import { ref, computed } from 'vue'; ...@@ -7,16 +8,16 @@ import { ref, computed } from 'vue';
export const useAppStore = defineStore('app', () => { export const useAppStore = defineStore('app', () => {
// 侧边栏状态 // 侧边栏状态
const sidebarCollapsed = ref(false); const sidebarCollapsed = ref(false);
// 主题模式 // 主题模式
const theme = ref<'light' | 'dark'>('light'); const theme = ref<'dark' | 'light'>('light');
// 加载状态 // 加载状态
const loading = ref(false); const loading = ref(false);
// 设备类型 // 设备类型
const device = ref<'desktop' | 'mobile'>('desktop'); const device = ref<'desktop' | 'mobile'>('desktop');
// 语言 // 语言
const language = ref('zh-CN'); const language = ref('zh-CN');
...@@ -44,15 +45,15 @@ export const useAppStore = defineStore('app', () => { ...@@ -44,15 +45,15 @@ export const useAppStore = defineStore('app', () => {
const toggleTheme = () => { const toggleTheme = () => {
theme.value = theme.value === 'light' ? 'dark' : 'light'; theme.value = theme.value === 'light' ? 'dark' : 'light';
// 应用主题到 document // 应用主题到 document
document.documentElement.setAttribute('data-theme', theme.value); document.documentElement.dataset.theme = theme.value;
}; };
/** /**
* 设置主题 * 设置主题
*/ */
const setTheme = (newTheme: 'light' | 'dark') => { const setTheme = (newTheme: 'dark' | 'light') => {
theme.value = newTheme; theme.value = newTheme;
document.documentElement.setAttribute('data-theme', newTheme); document.documentElement.dataset.theme = newTheme;
}; };
/** /**
...@@ -81,7 +82,7 @@ export const useAppStore = defineStore('app', () => { ...@@ -81,7 +82,7 @@ export const useAppStore = defineStore('app', () => {
*/ */
const initApp = () => { const initApp = () => {
// 从 localStorage 读取保存的主题 // 从 localStorage 读取保存的主题
const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null; const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null;
if (savedTheme) { if (savedTheme) {
setTheme(savedTheme); setTheme(savedTheme);
} }
...@@ -97,7 +98,7 @@ export const useAppStore = defineStore('app', () => { ...@@ -97,7 +98,7 @@ export const useAppStore = defineStore('app', () => {
const width = window.innerWidth; const width = window.innerWidth;
setDevice(width < 768 ? 'mobile' : 'desktop'); setDevice(width < 768 ? 'mobile' : 'desktop');
}; };
checkDevice(); checkDevice();
window.addEventListener('resize', checkDevice); window.addEventListener('resize', checkDevice);
}; };
...@@ -132,4 +133,3 @@ export const useAppStore = defineStore('app', () => { ...@@ -132,4 +133,3 @@ export const useAppStore = defineStore('app', () => {
saveAppState, saveAppState,
}; };
}); });
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* Pinia Stores 统一导出 * Pinia Stores 统一导出
*/ */
export { useUserStore } from './user';
export { usePermissionStore } from './permission';
export { useAppStore } from './app'; export { useAppStore } from './app';
export { usePermissionStore } from './permission';
export { useUserStore } from './user';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
import { ref } from 'vue';
import { defineStore } from 'pinia';
/** /**
* 权限路由管理 * 权限路由管理
*/ */
export const usePermissionStore = defineStore('permission', () => { export const usePermissionStore = defineStore('permission', () => {
// 所有路由 // 所有路由
const routes = ref<RouteRecordRaw[]>([]); const routes = ref<RouteRecordRaw[]>([]);
// 动态添加的路由 // 动态添加的路由
const dynamicRoutes = ref<RouteRecordRaw[]>([]); const dynamicRoutes = ref<RouteRecordRaw[]>([]);
// 是否已生成路由 // 是否已生成路由
const isRoutesGenerated = ref(false); const isRoutesGenerated = ref(false);
...@@ -29,13 +31,13 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -29,13 +31,13 @@ export const usePermissionStore = defineStore('permission', () => {
const generateRoutes = (roles: string[], permissions: string[]) => { const generateRoutes = (roles: string[], permissions: string[]) => {
// 这里可以根据角色和权限动态生成路由 // 这里可以根据角色和权限动态生成路由
// 目前先返回所有路由,后续可以根据需求扩展 // 目前先返回所有路由,后续可以根据需求扩展
// 示例:根据角色过滤路由 // 示例:根据角色过滤路由
const accessedRoutes = filterRoutes(routes.value, roles, permissions); const accessedRoutes = filterRoutes(routes.value, roles, permissions);
dynamicRoutes.value = accessedRoutes; dynamicRoutes.value = accessedRoutes;
isRoutesGenerated.value = true; isRoutesGenerated.value = true;
return accessedRoutes; return accessedRoutes;
}; };
...@@ -45,13 +47,13 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -45,13 +47,13 @@ export const usePermissionStore = defineStore('permission', () => {
const filterRoutes = ( const filterRoutes = (
routes: RouteRecordRaw[], routes: RouteRecordRaw[],
roles: string[], roles: string[],
permissions: string[] permissions: string[],
): RouteRecordRaw[] => { ): RouteRecordRaw[] => {
const res: RouteRecordRaw[] = []; const res: RouteRecordRaw[] = [];
routes.forEach(route => { routes.forEach((route) => {
const tmp = { ...route }; const tmp = { ...route };
// 检查路由权限 // 检查路由权限
if (hasPermission(tmp, roles, permissions)) { if (hasPermission(tmp, roles, permissions)) {
// 递归过滤子路由 // 递归过滤子路由
...@@ -71,7 +73,7 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -71,7 +73,7 @@ export const usePermissionStore = defineStore('permission', () => {
const hasPermission = ( const hasPermission = (
route: RouteRecordRaw, route: RouteRecordRaw,
roles: string[], roles: string[],
permissions: string[] permissions: string[],
): boolean => { ): boolean => {
// 如果路由没有设置权限要求,默认可访问 // 如果路由没有设置权限要求,默认可访问
if (!route.meta?.roles && !route.meta?.permissions) { if (!route.meta?.roles && !route.meta?.permissions) {
...@@ -81,7 +83,7 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -81,7 +83,7 @@ export const usePermissionStore = defineStore('permission', () => {
// 检查角色 // 检查角色
if (route.meta?.roles) { if (route.meta?.roles) {
const routeRoles = route.meta.roles as string[]; const routeRoles = route.meta.roles as string[];
if (roles.some(role => routeRoles.includes(role))) { if (roles.some((role) => routeRoles.includes(role))) {
return true; return true;
} }
} }
...@@ -89,7 +91,9 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -89,7 +91,9 @@ export const usePermissionStore = defineStore('permission', () => {
// 检查权限 // 检查权限
if (route.meta?.permissions) { if (route.meta?.permissions) {
const routePermissions = route.meta.permissions as string[]; const routePermissions = route.meta.permissions as string[];
if (permissions.some(permission => routePermissions.includes(permission))) { if (
permissions.some((permission) => routePermissions.includes(permission))
) {
return true; return true;
} }
} }
...@@ -116,4 +120,3 @@ export const usePermissionStore = defineStore('permission', () => { ...@@ -116,4 +120,3 @@ export const usePermissionStore = defineStore('permission', () => {
reset, reset,
}; };
}); });
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { login as loginApi, logout as logoutApi, getUserInfo as getUserInfoApi } from '@/api/user';
import { setToken, removeToken } from '@/utils/auth';
import type { LoginParams, UserInfo } from '@/types/user'; import type { LoginParams, UserInfo } from '@/types/user';
import { computed, ref } from 'vue';
import {
getUserInfo as getUserInfoApi,
login as loginApi,
logout as logoutApi,
} from '@/api/user';
import { removeToken, setToken } from '@/utils/auth';
import { defineStore } from 'pinia';
/** /**
* 用户状态管理 * 用户状态管理
*/ */
export const useUserStore = defineStore('user', () => { export const useUserStore = defineStore('user', () => {
// 状态 // 状态
const token = ref<string>(''); const token = ref<string>('');
const userInfo = ref<UserInfo | null>(null); const userInfo = ref<null | UserInfo>(null);
const permissions = ref<string[]>([]); const permissions = ref<string[]>([]);
const roles = ref<string[]>([]); const roles = ref<string[]>([]);
...@@ -65,7 +71,7 @@ export const useUserStore = defineStore('user', () => { ...@@ -65,7 +71,7 @@ export const useUserStore = defineStore('user', () => {
permissions.value = []; permissions.value = [];
roles.value = []; roles.value = [];
removeToken(); removeToken();
// 同步清空 qiankun 全局状态中的用户信息 // 同步清空 qiankun 全局状态中的用户信息
syncUserToQiankun(); syncUserToQiankun();
} }
...@@ -98,25 +104,30 @@ export const useUserStore = defineStore('user', () => { ...@@ -98,25 +104,30 @@ export const useUserStore = defineStore('user', () => {
*/ */
const syncUserToQiankun = () => { const syncUserToQiankun = () => {
// 延迟导入避免循环依赖 // 延迟导入避免循环依赖
import('@/qiankun/communication').then(({ communicationManager }) => { import('@/qiankun/communication')
if (userInfo.value) { .then(({ communicationManager }) => {
console.log('syncUserToQiankun.value', userInfo.value); if (userInfo.value) {
communicationManager.updateUser({ console.log('syncUserToQiankun.value', userInfo.value);
id: userInfo.value.id, communicationManager.updateUser({
name: userInfo.value.name, id: userInfo.value.id,
avatar: userInfo.value.avatar || '👨‍💼', name: userInfo.value.name,
role: roles.value[0] || 'user', avatar: userInfo.value.avatar || '👨‍💼',
permissions: permissions.value, role: roles.value[0] || 'user',
}); permissions: permissions.value,
console.log('[用户Store] 用户信息已同步到 qiankun 全局状态'); });
} else { console.log('[用户Store] 用户信息已同步到 qiankun 全局状态');
// 用户退出时,清空全局状态中的用户信息 } else {
communicationManager.updateUser(null); // 用户退出时,清空全局状态中的用户信息
console.log('[用户Store] 用户信息已清空'); communicationManager.updateUser(null);
} console.log('[用户Store] 用户信息已清空');
}).catch(err => { }
console.warn('[用户Store] qiankun 通信管理器未初始化或加载失败:', err); })
}); .catch((error) => {
console.warn(
'[用户Store] qiankun 通信管理器未初始化或加载失败:',
error,
);
});
}; };
/** /**
...@@ -132,7 +143,7 @@ export const useUserStore = defineStore('user', () => { ...@@ -132,7 +143,7 @@ export const useUserStore = defineStore('user', () => {
*/ */
const hasPermission = (permission: string | string[]): boolean => { const hasPermission = (permission: string | string[]): boolean => {
if (Array.isArray(permission)) { if (Array.isArray(permission)) {
return permission.some(p => permissions.value.includes(p)); return permission.some((p) => permissions.value.includes(p));
} }
return permissions.value.includes(permission); return permissions.value.includes(permission);
}; };
...@@ -142,7 +153,7 @@ export const useUserStore = defineStore('user', () => { ...@@ -142,7 +153,7 @@ export const useUserStore = defineStore('user', () => {
*/ */
const hasRole = (role: string | string[]): boolean => { const hasRole = (role: string | string[]): boolean => {
if (Array.isArray(role)) { if (Array.isArray(role)) {
return role.some(r => roles.value.includes(r)); return role.some((r) => roles.value.includes(r));
} }
return roles.value.includes(role); return roles.value.includes(role);
}; };
...@@ -180,4 +191,3 @@ export const useUserStore = defineStore('user', () => { ...@@ -180,4 +191,3 @@ export const useUserStore = defineStore('user', () => {
syncUserToQiankun, // 导出同步方法,供外部使用 syncUserToQiankun, // 导出同步方法,供外部使用
}; };
}); });
* { * {
margin: 0;
padding: 0;
box-sizing: border-box; box-sizing: border-box;
padding: 0;
margin: 0;
} }
html, html,
...@@ -9,9 +9,10 @@ body, ...@@ -9,9 +9,10 @@ body,
#app { #app {
width: 100%; width: 100%;
height: 100%; height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, font-family:
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
'Noto Color Emoji'; Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
font-size: 14px; font-size: 14px;
line-height: 1.5; line-height: 1.5;
color: #333; color: #333;
...@@ -19,12 +20,11 @@ body, ...@@ -19,12 +20,11 @@ body,
} }
a { a {
text-decoration: none;
color: inherit; color: inherit;
text-decoration: none;
} }
ul, ul,
ol { ol {
list-style: none; list-style: none;
} }
...@@ -41,4 +41,3 @@ export interface ApiError { ...@@ -41,4 +41,3 @@ export interface ApiError {
message: string; message: string;
details?: any; details?: any;
} }
...@@ -5,44 +5,44 @@ ...@@ -5,44 +5,44 @@
export interface MenuItem { export interface MenuItem {
/** 菜单唯一标识 */ /** 菜单唯一标识 */
id: string; id: string;
/** 菜单标题 */ /** 菜单标题 */
title: string; title: string;
/** 路由路径 */ /** 路由路径 */
path: string; path: string;
/** 菜单图标(可以是 emoji、图标类名或组件) */ /** 菜单图标(可以是 emoji、图标类名或组件) */
icon?: string; icon?: string;
/** 子菜单列表 */ /** 子菜单列表 */
children?: MenuItem[]; children?: MenuItem[];
/** 是否隐藏菜单项 */ /** 是否隐藏菜单项 */
hidden?: boolean; hidden?: boolean;
/** 菜单层级(1-一级,2-二级,3-三级) */ /** 菜单层级(1-一级,2-二级,3-三级) */
level?: number; level?: number;
/** 父级菜单ID */ /** 父级菜单ID */
parentId?: string; parentId?: string;
/** 扩展元数据 */ /** 扩展元数据 */
meta?: { meta?: {
/** 是否需要权限 */ /** 徽章数字 */
requireAuth?: boolean; badge?: number | string;
/** 权限标识 */
permission?: string;
/** 排序权重 */
order?: number;
/** 外部链接 */ /** 外部链接 */
externalLink?: string; externalLink?: string;
/** 是否在面包屑中显示 */
showInBreadcrumb?: boolean;
/** 是否缓存页面 */ /** 是否缓存页面 */
keepAlive?: boolean; keepAlive?: boolean;
/** 徽章数字 */ /** 排序权重 */
badge?: number | string; order?: number;
/** 权限标识 */
permission?: string;
/** 是否需要权限 */
requireAuth?: boolean;
/** 是否在面包屑中显示 */
showInBreadcrumb?: boolean;
}; };
} }
...@@ -53,16 +53,16 @@ export interface MenuItem { ...@@ -53,16 +53,16 @@ export interface MenuItem {
export interface TopMenuItem { export interface TopMenuItem {
/** 菜单唯一标识 */ /** 菜单唯一标识 */
id: string; id: string;
/** 菜单标题 */ /** 菜单标题 */
title: string; title: string;
/** 路由路径 */ /** 路由路径 */
path: string; path: string;
/** 菜单图标 */ /** 菜单图标 */
icon?: string; icon?: string;
/** 对应的侧边栏菜单 */ /** 对应的侧边栏菜单 */
sidebarMenus?: MenuItem[]; sidebarMenus?: MenuItem[];
} }
...@@ -73,8 +73,7 @@ export interface TopMenuItem { ...@@ -73,8 +73,7 @@ export interface TopMenuItem {
export interface BreadcrumbItem { export interface BreadcrumbItem {
/** 标题 */ /** 标题 */
title: string; title: string;
/** 路径 */ /** 路径 */
path?: string; path?: string;
} }
...@@ -67,4 +67,3 @@ export interface UpdateUserInfoParams { ...@@ -67,4 +67,3 @@ export interface UpdateUserInfoParams {
email?: string; email?: string;
phone?: string; phone?: string;
} }
...@@ -9,7 +9,7 @@ const USER_INFO_KEY = 'scrm_user_info'; ...@@ -9,7 +9,7 @@ const USER_INFO_KEY = 'scrm_user_info';
/** /**
* 获取 Token * 获取 Token
*/ */
export const getToken = (): string | null => { export const getToken = (): null | string => {
return localStorage.getItem(TOKEN_KEY); return localStorage.getItem(TOKEN_KEY);
}; };
...@@ -30,7 +30,7 @@ export const removeToken = (): void => { ...@@ -30,7 +30,7 @@ export const removeToken = (): void => {
/** /**
* 获取刷新令牌 * 获取刷新令牌
*/ */
export const getRefreshToken = (): string | null => { export const getRefreshToken = (): null | string => {
return localStorage.getItem(REFRESH_TOKEN_KEY); return localStorage.getItem(REFRESH_TOKEN_KEY);
}; };
...@@ -78,4 +78,3 @@ export const clearAuth = (): void => { ...@@ -78,4 +78,3 @@ export const clearAuth = (): void => {
removeRefreshToken(); removeRefreshToken();
removeUserInfoFromStorage(); removeUserInfoFromStorage();
}; };
...@@ -3,6 +3,5 @@ ...@@ -3,6 +3,5 @@
*/ */
export * from './auth'; export * from './auth';
export { del, get, patch, post, put, default as request } from './request';
export * from './storage'; export * from './storage';
export { default as request, get, post, put, del, patch } from './request';
...@@ -2,13 +2,19 @@ ...@@ -2,13 +2,19 @@
* Axios 请求封装 * Axios 请求封装
*/ */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'; import axios, {
import { getToken, clearAuth } from './auth'; AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
} from 'axios';
import { clearAuth, getToken } from './auth';
// 创建 axios 实例 // 创建 axios 实例
const service: AxiosInstance = axios.create({ const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '/api', baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 30000, timeout: 30_000,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
...@@ -20,7 +26,7 @@ service.interceptors.request.use( ...@@ -20,7 +26,7 @@ service.interceptors.request.use(
// 添加 token // 添加 token
const token = getToken(); const token = getToken();
if (token && config.headers) { if (token && config.headers) {
config.headers['Authorization'] = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
// 添加时间戳防止缓存 // 添加时间戳防止缓存
...@@ -36,7 +42,7 @@ service.interceptors.request.use( ...@@ -36,7 +42,7 @@ service.interceptors.request.use(
(error: AxiosError) => { (error: AxiosError) => {
console.error('请求错误:', error); console.error('请求错误:', error);
return Promise.reject(error); return Promise.reject(error);
} },
); );
// 响应拦截器 // 响应拦截器
...@@ -71,20 +77,25 @@ service.interceptors.response.use( ...@@ -71,20 +77,25 @@ service.interceptors.response.use(
const { status, data } = error.response; const { status, data } = error.response;
switch (status) { switch (status) {
case 401: case 401: {
handleUnauthorized(); handleUnauthorized();
break; break;
case 403: }
case 403: {
console.error('无权限访问'); console.error('无权限访问');
break; break;
case 404: }
case 404: {
console.error('请求的资源不存在'); console.error('请求的资源不存在');
break; break;
case 500: }
case 500: {
console.error('服务器内部错误'); console.error('服务器内部错误');
break; break;
default: }
default: {
console.error('请求失败:', data); console.error('请求失败:', data);
}
} }
} else if (error.request) { } else if (error.request) {
console.error('网络错误,请检查网络连接'); console.error('网络错误,请检查网络连接');
...@@ -93,7 +104,7 @@ service.interceptors.response.use( ...@@ -93,7 +104,7 @@ service.interceptors.response.use(
} }
return Promise.reject(error); return Promise.reject(error);
} },
); );
/** /**
...@@ -102,7 +113,7 @@ service.interceptors.response.use( ...@@ -102,7 +113,7 @@ service.interceptors.response.use(
const handleUnauthorized = () => { const handleUnauthorized = () => {
console.warn('登录已过期,请重新登录'); console.warn('登录已过期,请重新登录');
clearAuth(); clearAuth();
// 跳转到登录页 // 跳转到登录页
if (window.location.pathname !== '/login') { if (window.location.pathname !== '/login') {
window.location.href = '/login'; window.location.href = '/login';
...@@ -119,37 +130,56 @@ export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => { ...@@ -119,37 +130,56 @@ export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
/** /**
* GET 请求 * GET 请求
*/ */
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => { export const get = <T = any>(
url: string,
params?: any,
config?: AxiosRequestConfig,
): Promise<T> => {
return service.get(url, { params, ...config }); return service.get(url, { params, ...config });
}; };
/** /**
* POST 请求 * POST 请求
*/ */
export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => { export const post = <T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T> => {
return service.post(url, data, config); return service.post(url, data, config);
}; };
/** /**
* PUT 请求 * PUT 请求
*/ */
export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => { export const put = <T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T> => {
return service.put(url, data, config); return service.put(url, data, config);
}; };
/** /**
* DELETE 请求 * DELETE 请求
*/ */
export const del = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => { export const del = <T = any>(
url: string,
params?: any,
config?: AxiosRequestConfig,
): Promise<T> => {
return service.delete(url, { params, ...config }); return service.delete(url, { params, ...config });
}; };
/** /**
* PATCH 请求 * PATCH 请求
*/ */
export const patch = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => { export const patch = <T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T> => {
return service.patch(url, data, config); return service.patch(url, data, config);
}; };
export default service; export default service;
...@@ -6,6 +6,13 @@ ...@@ -6,6 +6,13 @@
type StorageType = 'local' | 'session'; type StorageType = 'local' | 'session';
class Storage { class Storage {
/**
* 获取存储项数量
*/
get length(): number {
return this.storage.length;
}
private storage: globalThis.Storage; private storage: globalThis.Storage;
constructor(type: StorageType = 'local') { constructor(type: StorageType = 'local') {
...@@ -13,20 +20,20 @@ class Storage { ...@@ -13,20 +20,20 @@ class Storage {
} }
/** /**
* 设置存储项 * 清空所有存储项
*/ */
set(key: string, value: any): void { clear(): void {
try { try {
const serializedValue = JSON.stringify(value); this.storage.clear();
this.storage.setItem(key, serializedValue);
} catch (error) { } catch (error) {
console.error('清空存储失败:', error);
} }
} }
/** /**
* 获取存储项 * 获取存储项
*/ */
get<T = any>(key: string): T | null { get<T = any>(key: string): null | T {
try { try {
const item = this.storage.getItem(key); const item = this.storage.getItem(key);
return item ? JSON.parse(item) : null; return item ? JSON.parse(item) : null;
...@@ -37,25 +44,24 @@ class Storage { ...@@ -37,25 +44,24 @@ class Storage {
} }
/** /**
* 移除存储项 * 获取带过期时间的存储项
*/ */
remove(key: string): void { getWithExpiry<T = any>(key: string): null | T {
try { const item = this.get<{ expiry: number; value: T }>(key);
this.storage.removeItem(key);
} catch (error) { if (!item) {
console.error('移除数据失败:', error); return null;
} }
}
/** const now = Date.now();
* 清空所有存储项
*/ // 检查是否过期
clear(): void { if (now > item.expiry) {
try { this.remove(key);
this.storage.clear(); return null;
} catch (error) {
console.error('清空存储失败:', error);
} }
return item.value;
} }
/** /**
...@@ -73,44 +79,37 @@ class Storage { ...@@ -73,44 +79,37 @@ class Storage {
} }
/** /**
* 获取存储项数量 * 移除存储项
*/ */
get length(): number { remove(key: string): void {
return this.storage.length; try {
this.storage.removeItem(key);
} catch (error) {
console.error('移除数据失败:', error);
}
}
/**
* 设置存储项
*/
set(key: string, value: any): void {
try {
const serializedValue = JSON.stringify(value);
this.storage.setItem(key, serializedValue);
} catch {}
} }
/** /**
* 设置带过期时间的存储项 * 设置带过期时间的存储项
*/ */
setWithExpiry(key: string, value: any, expiryInMs: number): void { setWithExpiry(key: string, value: any, expiryInMs: number): void {
const now = new Date().getTime(); const now = Date.now();
const item = { const item = {
value, value,
expiry: now + expiryInMs, expiry: now + expiryInMs,
}; };
this.set(key, item); this.set(key, item);
} }
/**
* 获取带过期时间的存储项
*/
getWithExpiry<T = any>(key: string): T | null {
const item = this.get<{ value: T; expiry: number }>(key);
if (!item) {
return null;
}
const now = new Date().getTime();
// 检查是否过期
if (now > item.expiry) {
this.remove(key);
return null;
}
return item.value;
}
} }
// 导出实例 // 导出实例
...@@ -118,4 +117,3 @@ export const localCache = new Storage('local'); ...@@ -118,4 +117,3 @@ export const localCache = new Storage('local');
export const sessionCache = new Storage('session'); export const sessionCache = new Storage('session');
export default Storage; export default Storage;
<template>
<!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 -->
<div id="subapp-container" class="micro-app-container"></div>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'; import { onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
...@@ -18,14 +13,19 @@ onUnmounted(() => { ...@@ -18,14 +13,19 @@ onUnmounted(() => {
}); });
</script> </script>
<template>
<!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 -->
<div id="subapp-container" class="micro-app-container"></div>
</template>
<style scoped> <style scoped>
.micro-app-container { .micro-app-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
min-height: 500px; min-height: 500px;
/* 移除内边距,让微应用完全填充容器 */ /* 移除内边距,让微应用完全填充容器 */
padding: 0; padding: 0;
margin: 0; margin: 0;
} }
</style> </style>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/home');
};
</script>
<template> <template>
<div class="not-found-page"> <div class="not-found-page">
<div class="not-found-content"> <div class="not-found-content">
...@@ -9,16 +19,6 @@ ...@@ -9,16 +19,6 @@
</div> </div>
</template> </template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/home');
};
</script>
<style scoped> <style scoped>
.not-found-page { .not-found-page {
display: flex; display: flex;
...@@ -29,27 +29,27 @@ const goHome = () => { ...@@ -29,27 +29,27 @@ const goHome = () => {
} }
.not-found-content { .not-found-content {
text-align: center;
color: #fff; color: #fff;
text-align: center;
} }
.error-code { .error-code {
margin-bottom: 24px;
font-size: 120px; font-size: 120px;
font-weight: 700; font-weight: 700;
line-height: 1; line-height: 1;
margin-bottom: 24px; text-shadow: 0 4px 8px rgb(0 0 0 / 20%);
text-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
} }
.error-title { .error-title {
margin-bottom: 16px;
font-size: 32px; font-size: 32px;
font-weight: 600; font-weight: 600;
margin-bottom: 16px;
} }
.error-desc { .error-desc {
font-size: 16px;
margin-bottom: 32px; margin-bottom: 32px;
font-size: 16px;
opacity: 0.9; opacity: 0.9;
} }
...@@ -58,17 +58,16 @@ const goHome = () => { ...@@ -58,17 +58,16 @@ const goHome = () => {
font-size: 16px; font-size: 16px;
font-weight: 500; font-weight: 500;
color: #667eea; color: #667eea;
cursor: pointer;
background: #fff; background: #fff;
border: none; border: none;
border-radius: 24px; border-radius: 24px;
cursor: pointer; box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
transition: all 0.3s; transition: all 0.3s;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
} }
.back-button:hover { .back-button:hover {
box-shadow: 0 6px 16px rgb(0 0 0 / 20%);
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
} }
</style> </style>
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2020", "target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true, "useDefineForClassFields": true,
/* Path alias */
"baseUrl": ".",
"module": "ESNext", "module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */ /* Bundler mode */
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowImportingTsExtensions": true, "paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "allowImportingTsExtensions": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */ /* Linting */
"strict": true, "strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true, "noEmit": true,
"isolatedModules": true,
/* Path alias */ "skipLibCheck": true
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}, },
"include": ["env.d.ts", "src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }],
"references": [{ "path": "./tsconfig.node.json" }] "include": [
"env.d.ts",
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue"
]
} }
{ {
"compilerOptions": { "compilerOptions": {
"composite": true, "composite": true,
"skipLibCheck": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowSyntheticDefaultImports": true "allowSyntheticDefaultImports": true,
"skipLibCheck": true
}, },
"include": ["vite.config.ts"] "include": ["vite.config.ts"]
} }
import { defineConfig } from 'vite'; import { resolve } from 'node:path';
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx'; import vueJsx from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite'; import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'; import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig } from 'vite';
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
...@@ -36,4 +37,3 @@ export default defineConfig({ ...@@ -36,4 +37,3 @@ export default defineConfig({
cssCodeSplit: false, cssCodeSplit: false,
}, },
}); });
/// <reference types="vite/client" /> // / <reference types="vite/client" />
declare module '*.vue' { declare module '*.vue' {
import type { DefineComponent } from 'vue'; import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
...@@ -15,4 +16,3 @@ declare global { ...@@ -15,4 +16,3 @@ declare global {
} }
export {}; export {};
{ {
"name": "@venus/venus-micro-app", "name": "@venus/venus-micro-app",
"version": "1.0.0", "version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"scripts": { "scripts": {
"dev": "vite --port 8081 --host", "dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build", "build": "vue-tsc && vite build",
...@@ -11,22 +11,22 @@ ...@@ -11,22 +11,22 @@
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"vue": "catalog:", "@venus/common-ui-vue": "workspace:*",
"vue-router": "catalog:",
"pinia": "catalog:",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"axios": "catalog:" "axios": "catalog:",
"pinia": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:", "@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:", "@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:", "typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:",
"unplugin-auto-import": "catalog:", "unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:", "unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:", "vite-plugin-qiankun": "catalog:",
"@types/node": "catalog:" "vue-tsc": "catalog:"
} }
} }
import { createApp } from 'vue'; import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper';
import type { App as VueApp } from 'vue'; import type { App as VueApp } from 'vue';
import { createApp } from 'vue';
import { createPinia } from 'pinia'; import { createPinia } from 'pinia';
import { createRouter } from './router';
import { import {
renderWithQiankun,
qiankunWindow, qiankunWindow,
type QiankunProps, renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper'; } from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue'; import App from './App.vue';
import { createRouter } from './router';
import './style.css'; import './style.css';
let app: VueApp<Element> | null = null; let app: null | VueApp<Element> = null;
let router: any = null; let router: any = null;
/** /**
...@@ -19,34 +24,34 @@ let router: any = null; ...@@ -19,34 +24,34 @@ let router: any = null;
*/ */
async function render(props: QiankunProps = {}) { async function render(props: QiankunProps = {}) {
const { container } = props; const { container } = props;
app = createApp(App); app = createApp(App);
// 配置 Pinia // 配置 Pinia
app.use(createPinia()); app.use(createPinia());
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base // 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? (props.routerBase || '/subapp-vue') ? props.routerBase || '/subapp-vue'
: '/'; : '/';
router = createRouter(routerBase); router = createRouter(routerBase);
app.use(router); app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中) // 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) { if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.init(props); subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用 // 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication; app.config.globalProperties.$communication = subAppCommunication;
} }
// 挂载应用 // 挂载应用
const containerEl = container const containerEl = container
? container.querySelector('#app') ? container.querySelector('#app')
: document.getElementById('app'); : document.querySelector('#app');
if (containerEl) { if (containerEl) {
app.mount(containerEl as Element); app.mount(containerEl as Element);
} else { } else {
...@@ -86,13 +91,13 @@ export async function mount(props: QiankunProps) { ...@@ -86,13 +91,13 @@ export async function mount(props: QiankunProps) {
*/ */
export async function unmount(props: QiankunProps) { export async function unmount(props: QiankunProps) {
console.log('[Vue3 微应用] unmount', props); console.log('[Vue3 微应用] unmount', props);
// 销毁通信管理器 // 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.destroy(); subAppCommunication.destroy();
} }
if (app) { if (app) {
app.unmount(); app.unmount();
app = null; app = null;
...@@ -117,4 +122,3 @@ renderWithQiankun({ ...@@ -117,4 +122,3 @@ renderWithQiankun({
unmount, unmount,
update, update,
}); });
import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router'; import { createRouter as _createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw, Router } from 'vue-router';
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
{ {
...@@ -74,4 +75,3 @@ export function createRouter(base: string = '/'): Router { ...@@ -74,4 +75,3 @@ export function createRouter(base: string = '/'): Router {
return router; return router;
} }
...@@ -5,31 +5,29 @@ ...@@ -5,31 +5,29 @@
:root { :root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400; font-weight: 400;
line-height: 1.5;
color-scheme: light dark; color-scheme: light dark;
font-synthesis: none; font-synthesis: none;
text-rendering: optimizeLegibility; text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
html, html,
body { body {
margin: 0;
padding: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
padding: 0;
margin: 0;
} }
body { body {
margin: 0;
display: flex; display: flex;
place-items: center; place-items: center;
min-width: 320px; min-width: 320px;
min-height: 100vh; min-height: 100vh;
margin: 0;
} }
#app { #app {
...@@ -44,22 +42,22 @@ body { ...@@ -44,22 +42,22 @@ body {
} }
::-webkit-scrollbar-track { ::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1); background: rgb(255 255 255 / 10%);
} }
::-webkit-scrollbar-thumb { ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3); background: rgb(255 255 255 / 30%);
border-radius: 4px; border-radius: 4px;
} }
::-webkit-scrollbar-thumb:hover { ::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5); background: rgb(255 255 255 / 50%);
} }
/* 选中文本样式 */ /* 选中文本样式 */
::selection { ::selection {
background: rgba(255, 255, 255, 0.3);
color: white; color: white;
background: rgb(255 255 255 / 30%);
} }
/* 响应式 */ /* 响应式 */
...@@ -68,4 +66,3 @@ body { ...@@ -68,4 +66,3 @@ body {
font-size: 14px; font-size: 14px;
} }
} }
...@@ -4,35 +4,35 @@ import { onUnmounted } from 'vue'; ...@@ -4,35 +4,35 @@ import { onUnmounted } from 'vue';
* 全局状态接口定义(与基座保持一致) * 全局状态接口定义(与基座保持一致)
*/ */
export interface GlobalState { export interface GlobalState {
user: { user: null | {
avatar: string;
id: string; id: string;
name: string; name: string;
avatar: string;
role: string;
permissions: string[]; permissions: string[];
} | null; role: string;
};
theme: { theme: {
mode: 'light' | 'dark'; mode: 'dark' | 'light';
primaryColor: string; primaryColor: string;
}; };
notifications: Notification[]; notifications: Notification[];
config: { config: {
apiBaseUrl: string; apiBaseUrl: string;
timeout: number; timeout: number;
}; };
// 当前激活的菜单信息 // 当前激活的菜单信息
currentMenu?: { currentMenu?: null | {
menuId: string;
menuTitle: string;
menuPath: string;
menuIcon?: string; menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>; menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
timestamp: number; timestamp: number;
} | null; };
} }
/** /**
...@@ -40,7 +40,7 @@ export interface GlobalState { ...@@ -40,7 +40,7 @@ export interface GlobalState {
*/ */
export interface Notification { export interface Notification {
id: string; id: string;
type: 'success' | 'warning' | 'error' | 'info'; type: 'error' | 'info' | 'success' | 'warning';
title: string; title: string;
message: string; message: string;
timestamp: number; timestamp: number;
...@@ -55,7 +55,7 @@ export interface QiankunProps { ...@@ -55,7 +55,7 @@ export interface QiankunProps {
routerBase?: string; routerBase?: string;
onGlobalStateChange?: ( onGlobalStateChange?: (
callback: (state: GlobalState, prev: GlobalState) => void, callback: (state: GlobalState, prev: GlobalState) => void,
fireImmediately?: boolean fireImmediately?: boolean,
) => void; ) => void;
setGlobalState?: (state: Partial<GlobalState>) => void; setGlobalState?: (state: Partial<GlobalState>) => void;
[key: string]: any; [key: string]: any;
...@@ -65,10 +65,31 @@ export interface QiankunProps { ...@@ -65,10 +65,31 @@ export interface QiankunProps {
* 子应用通信管理器 * 子应用通信管理器
*/ */
class SubAppCommunicationManager { class SubAppCommunicationManager {
private props: QiankunProps | null = null;
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> = [];
private unsubscribe: (() => void) | null = null;
private currentState: GlobalState | null = null; // 缓存当前状态 private currentState: GlobalState | null = null; // 缓存当前状态
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[];
private props: null | QiankunProps = null;
private unsubscribe: (() => void) | null = null;
/**
* 销毁
*/
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
this.listeners = [];
this.props = null;
console.log('[子应用通信] 通信管理器已销毁');
}
/**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/** /**
* 初始化通信管理器 * 初始化通信管理器
...@@ -82,16 +103,16 @@ class SubAppCommunicationManager { ...@@ -82,16 +103,16 @@ class SubAppCommunicationManager {
const unsubscribeFn = props.onGlobalStateChange( const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => { (state: GlobalState, prev: GlobalState) => {
console.log('[子应用通信] 全局状态变化:', state, prev); console.log('[子应用通信] 全局状态变化:', state, prev);
// 缓存当前状态 // 缓存当前状态
this.currentState = state; this.currentState = state;
// 触发所有监听器 // 触发所有监听器
this.listeners.forEach(listener => { this.listeners.forEach((listener) => {
listener(state, prev); listener(state, prev);
}); });
}, },
true // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据 true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
); );
// 只在返回值是函数时才赋值 // 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') { if (typeof unsubscribeFn === 'function') {
...@@ -100,7 +121,7 @@ class SubAppCommunicationManager { ...@@ -100,7 +121,7 @@ class SubAppCommunicationManager {
} }
console.log('[子应用通信] 通信管理器初始化完成'); console.log('[子应用通信] 通信管理器初始化完成');
// 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递 // 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递
setTimeout(() => { setTimeout(() => {
if (this.props?.onGlobalStateChange) { if (this.props?.onGlobalStateChange) {
...@@ -110,48 +131,30 @@ class SubAppCommunicationManager { ...@@ -110,48 +131,30 @@ class SubAppCommunicationManager {
} }
/** /**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/**
* 监听全局状态变化 * 监听全局状态变化
* @param callback 回调函数 * @param callback 回调函数
* @returns 取消监听的函数 * @returns 取消监听的函数
*/ */
onStateChange(callback: (state: GlobalState, prev: GlobalState) => void): () => void { onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback); this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调 // 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) { if (this.currentState) {
console.log('[子应用通信] 立即触发回调,使用缓存的全局状态'); console.log('[子应用通信] 立即触发回调,使用缓存的全局状态');
callback(this.currentState, {} as GlobalState); callback(this.currentState, {} as GlobalState);
} }
return () => { return () => {
const index = this.listeners.indexOf(callback); const index = this.listeners.indexOf(callback);
if (index > -1) { if (index !== -1) {
this.listeners.splice(index, 1); this.listeners.splice(index, 1);
} }
}; };
} }
/** /**
* 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) {
this.props.setGlobalState(state);
console.log('[子应用通信] 全局状态已更新:', state);
} else {
console.warn('[子应用通信] setGlobalState 方法不可用');
}
}
/**
* 向基座发送通知 * 向基座发送通知
* @param notification 通知消息 * @param notification 通知消息
*/ */
...@@ -179,16 +182,16 @@ class SubAppCommunicationManager { ...@@ -179,16 +182,16 @@ class SubAppCommunicationManager {
} }
/** /**
* 销毁 * 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/ */
destroy() { setGlobalState(state: Partial<GlobalState>) {
if (this.unsubscribe) { if (this.props?.setGlobalState) {
this.unsubscribe(); this.props.setGlobalState(state);
this.unsubscribe = null; console.log('[子应用通信] 全局状态已更新:', state);
} else {
console.warn('[子应用通信] setGlobalState 方法不可用');
} }
this.listeners = [];
this.props = null;
console.log('[子应用通信] 通信管理器已销毁');
} }
} }
...@@ -200,15 +203,15 @@ export const subAppCommunication = new SubAppCommunicationManager(); ...@@ -200,15 +203,15 @@ export const subAppCommunication = new SubAppCommunicationManager();
* @param callback 状态变化回调 * @param callback 状态变化回调
*/ */
export function useGlobalState( export function useGlobalState(
callback: (state: GlobalState, prev: GlobalState) => void callback: (state: GlobalState, prev: GlobalState) => void,
) { ) {
const unsubscribe = subAppCommunication.onStateChange(callback); const unsubscribe = subAppCommunication.onStateChange(callback);
// 在组件卸载时自动取消订阅 // 在组件卸载时自动取消订阅
onUnmounted(() => { onUnmounted(() => {
unsubscribe(); unsubscribe();
}); });
return unsubscribe; return unsubscribe;
} }
...@@ -218,7 +221,7 @@ export function useGlobalState( ...@@ -218,7 +221,7 @@ export function useGlobalState(
export function notify( export function notify(
type: Notification['type'], type: Notification['type'],
title: string, title: string,
message: string message: string,
) { ) {
subAppCommunication.sendNotification({ subAppCommunication.sendNotification({
type, type,
...@@ -226,4 +229,3 @@ export function notify( ...@@ -226,4 +229,3 @@ export function notify(
message, message,
}); });
} }
<script setup lang="ts">
// About 页面
</script>
<template> <template>
<div class="about-view"> <div class="about-view">
<div class="content-card"> <div class="content-card">
<h1>📖 关于本应用</h1> <h1>📖 关于本应用</h1>
<section class="section"> <section class="section">
<h2>技术栈</h2> <h2>技术栈</h2>
<ul class="tech-list"> <ul class="tech-list">
...@@ -44,10 +48,6 @@ pnpm build</code></pre> ...@@ -44,10 +48,6 @@ pnpm build</code></pre>
</div> </div>
</template> </template>
<script setup lang="ts">
// About 页面
</script>
<style scoped> <style scoped>
.about-view { .about-view {
max-width: 900px; max-width: 900px;
...@@ -55,15 +55,15 @@ pnpm build</code></pre> ...@@ -55,15 +55,15 @@ pnpm build</code></pre>
} }
.content-card { .content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem; padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);
} }
.content-card h1 { .content-card h1 {
margin: 0 0 2rem 0; margin: 0 0 2rem;
font-size: 2rem; font-size: 2rem;
} }
...@@ -72,31 +72,31 @@ pnpm build</code></pre> ...@@ -72,31 +72,31 @@ pnpm build</code></pre>
} }
.section h2 { .section h2 {
margin: 0 0 1rem 0; margin: 0 0 1rem;
font-size: 1.5rem; font-size: 1.5rem;
color: rgba(255, 255, 255, 0.95); color: rgb(255 255 255 / 95%);
} }
.tech-list, .tech-list,
.feature-list { .feature-list {
list-style: none;
padding: 0; padding: 0;
margin: 0; margin: 0;
list-style: none;
} }
.tech-list li, .tech-list li,
.feature-list li { .feature-list li {
padding: 0.5rem 0; padding: 0.5rem 0;
opacity: 0.9;
line-height: 1.6; line-height: 1.6;
opacity: 0.9;
} }
.code-block { .code-block {
background: rgba(0, 0, 0, 0.3);
padding: 1.5rem; padding: 1.5rem;
border-radius: 0.5rem;
border: 1px solid rgba(255, 255, 255, 0.1);
overflow-x: auto; overflow-x: auto;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.5rem;
} }
.code-block pre { .code-block pre {
...@@ -110,4 +110,3 @@ pnpm build</code></pre> ...@@ -110,4 +110,3 @@ pnpm build</code></pre>
color: #a8e6cf; color: #a8e6cf;
} }
</style> </style>
<script setup lang="ts">
import type { GlobalState } from '@/utils/communication';
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { notify, useGlobalState } from '@/utils/communication';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
const route = useRoute();
const counter = ref(0);
const globalState = ref<GlobalState | null>(null);
const runMode = computed(() => {
return qiankunWindow.__POWERED_BY_QIANKUN__ ? '🔗 基座模式' : '🏠 独立模式';
});
const currentRoute = computed(() => route.fullPath);
const increment = () => {
counter.value++;
};
const decrement = () => {
counter.value--;
};
// 监听主应用传递的全局状态
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
useGlobalState((state, prev) => {
console.log('📥 接收到主应用数据:', state);
console.log('📝 之前的数据:', prev);
globalState.value = state;
});
}
// 发送测试通知到主应用
const sendTestNotification = () => {
notify(
'success',
'来自微应用的通知',
`这是一条测试通知,发送时间: ${new Date().toLocaleTimeString()}`,
);
};
</script>
<template> <template>
<div class="home-view"> <div class="home-view">
<div class="hero-section"> <div class="hero-section">
...@@ -77,7 +123,9 @@ ...@@ -77,7 +123,9 @@
</div> </div>
<div class="info-item"> <div class="info-item">
<span class="info-label">权限:</span> <span class="info-label">权限:</span>
<span class="info-value">{{ globalState.user.permissions.join(', ') }}</span> <span class="info-value">{{
globalState.user.permissions.join(', ')
}}</span>
</div> </div>
</div> </div>
...@@ -112,10 +160,23 @@ ...@@ -112,10 +160,23 @@
</div> </div>
<!-- 通知消息 --> <!-- 通知消息 -->
<div v-if="globalState?.notifications && globalState.notifications.length > 0" class="data-group"> <div
<h3 class="data-group-title">📢 通知消息 ({{ globalState.notifications.length }})</h3> v-if="
<div v-for="notification in globalState.notifications.slice(0, 3)" :key="notification.id" class="notification-item"> globalState?.notifications && globalState.notifications.length > 0
<span :class="['notification-type', notification.type]">{{ notification.type }}</span> "
class="data-group"
>
<h3 class="data-group-title">
📢 通知消息 ({{ globalState.notifications.length }})
</h3>
<div
v-for="notification in globalState.notifications.slice(0, 3)"
:key="notification.id"
class="notification-item"
>
<span class="notification-type" :class="[notification.type]">{{
notification.type
}}</span>
<span class="notification-title">{{ notification.title }}</span> <span class="notification-title">{{ notification.title }}</span>
<span class="notification-from" v-if="notification.from">来自: {{ notification.from }}</span> <span class="notification-from" v-if="notification.from">来自: {{ notification.from }}</span>
</div> </div>
...@@ -137,49 +198,6 @@ ...@@ -137,49 +198,6 @@
</div> </div>
</template> </template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import { useGlobalState, notify, type GlobalState } from '@/utils/communication';
const route = useRoute();
const counter = ref(0);
const globalState = ref<GlobalState | null>(null);
const runMode = computed(() => {
return qiankunWindow.__POWERED_BY_QIANKUN__ ? '🔗 基座模式' : '🏠 独立模式';
});
const currentRoute = computed(() => route.fullPath);
const increment = () => {
counter.value++;
};
const decrement = () => {
counter.value--;
};
// 监听主应用传递的全局状态
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
useGlobalState((state, prev) => {
console.log('📥 接收到主应用数据:', state);
console.log('📝 之前的数据:', prev);
globalState.value = state;
});
}
// 发送测试通知到主应用
const sendTestNotification = () => {
notify(
'success',
'来自微应用的通知',
`这是一条测试通知,发送时间: ${new Date().toLocaleTimeString()}`
);
};
</script>
<style scoped> <style scoped>
.home-view { .home-view {
max-width: 1200px; max-width: 1200px;
...@@ -187,14 +205,14 @@ const sendTestNotification = () => { ...@@ -187,14 +205,14 @@ const sendTestNotification = () => {
} }
.hero-section { .hero-section {
text-align: center;
padding: 3rem 0; padding: 3rem 0;
margin-bottom: 3rem; margin-bottom: 3rem;
text-align: center;
} }
.hero-title { .hero-title {
font-size: 2.5rem;
margin-bottom: 1rem; margin-bottom: 1rem;
font-size: 2.5rem;
font-weight: 700; font-weight: 700;
} }
...@@ -211,27 +229,27 @@ const sendTestNotification = () => { ...@@ -211,27 +229,27 @@ const sendTestNotification = () => {
} }
.card { .card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2rem; padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.card:hover { .card:hover {
background: rgb(255 255 255 / 15%);
box-shadow: 0 10px 30px rgb(0 0 0 / 20%);
transform: translateY(-5px); transform: translateY(-5px);
background: rgba(255, 255, 255, 0.15);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
} }
.card-icon { .card-icon {
font-size: 3rem;
margin-bottom: 1rem; margin-bottom: 1rem;
font-size: 3rem;
} }
.card h3 { .card h3 {
margin: 0 0 0.5rem 0; margin: 0 0 0.5rem;
font-size: 1.3rem; font-size: 1.3rem;
} }
...@@ -241,15 +259,15 @@ const sendTestNotification = () => { ...@@ -241,15 +259,15 @@ const sendTestNotification = () => {
} }
.info-section { .info-section {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2rem; padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);
} }
.info-section h2 { .info-section h2 {
margin: 0 0 1.5rem 0; margin: 0 0 1.5rem;
font-size: 1.5rem; font-size: 1.5rem;
} }
...@@ -261,56 +279,56 @@ const sendTestNotification = () => { ...@@ -261,56 +279,56 @@ const sendTestNotification = () => {
.info-item { .info-item {
display: flex; display: flex;
align-items: center;
gap: 1rem; gap: 1rem;
align-items: center;
} }
.info-label { .info-label {
font-weight: 600;
min-width: 100px; min-width: 100px;
font-weight: 600;
} }
.info-value { .info-value {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 0.5rem;
font-family: monospace; font-family: monospace;
background: rgb(255 255 255 / 10%);
border-radius: 0.5rem;
} }
.btn-primary, .btn-primary,
.btn-secondary { .btn-secondary {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
font-weight: 600;
cursor: pointer;
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-primary { .btn-primary {
background: rgba(76, 175, 80, 0.8);
color: white; color: white;
background: rgb(76 175 80 / 80%);
} }
.btn-primary:hover { .btn-primary:hover {
background: rgba(76, 175, 80, 1); background: rgb(76 175 80 / 100%);
} }
.btn-secondary { .btn-secondary {
background: rgba(244, 67, 54, 0.8);
color: white; color: white;
background: rgb(244 67 54 / 80%);
} }
.btn-secondary:hover { .btn-secondary:hover {
background: rgba(244, 67, 54, 1); background: rgb(244 67 54 / 100%);
} }
.data-group { .data-group {
margin-bottom: 1.5rem;
padding: 1rem; padding: 1rem;
background: rgba(255, 255, 255, 0.05); margin-bottom: 1.5rem;
background: rgb(255 255 255 / 5%);
border-left: 3px solid rgb(255 255 255 / 30%);
border-radius: 0.5rem; border-radius: 0.5rem;
border-left: 3px solid rgba(255, 255, 255, 0.3);
} }
.data-group:last-child { .data-group:last-child {
...@@ -318,7 +336,7 @@ const sendTestNotification = () => { ...@@ -318,7 +336,7 @@ const sendTestNotification = () => {
} }
.data-group-title { .data-group-title {
margin: 0 0 1rem 0; margin: 0 0 1rem;
font-size: 1.1rem; font-size: 1.1rem;
font-weight: 600; font-weight: 600;
opacity: 0.9; opacity: 0.9;
...@@ -326,12 +344,12 @@ const sendTestNotification = () => { ...@@ -326,12 +344,12 @@ const sendTestNotification = () => {
.notification-item { .notification-item {
display: flex; display: flex;
align-items: center;
gap: 0.75rem; gap: 0.75rem;
align-items: center;
padding: 0.75rem; padding: 0.75rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 0.375rem;
margin-bottom: 0.5rem; margin-bottom: 0.5rem;
background: rgb(255 255 255 / 5%);
border-radius: 0.375rem;
} }
.notification-item:last-child { .notification-item:last-child {
...@@ -340,30 +358,30 @@ const sendTestNotification = () => { ...@@ -340,30 +358,30 @@ const sendTestNotification = () => {
.notification-type { .notification-type {
padding: 0.25rem 0.5rem; padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.75rem; font-size: 0.75rem;
font-weight: 600; font-weight: 600;
text-transform: uppercase; text-transform: uppercase;
border-radius: 0.25rem;
} }
.notification-type.success { .notification-type.success {
background: rgba(76, 175, 80, 0.2); color: rgb(76 175 80);
color: rgb(76, 175, 80); background: rgb(76 175 80 / 20%);
} }
.notification-type.warning { .notification-type.warning {
background: rgba(255, 152, 0, 0.2); color: rgb(255 152 0);
color: rgb(255, 152, 0); background: rgb(255 152 0 / 20%);
} }
.notification-type.error { .notification-type.error {
background: rgba(244, 67, 54, 0.2); color: rgb(244 67 54);
color: rgb(244, 67, 54); background: rgb(244 67 54 / 20%);
} }
.notification-type.info { .notification-type.info {
background: rgba(33, 150, 243, 0.2); color: rgb(33 150 243);
color: rgb(33, 150, 243); background: rgb(33 150 243 / 20%);
} }
.notification-title { .notification-title {
...@@ -377,8 +395,8 @@ const sendTestNotification = () => { ...@@ -377,8 +395,8 @@ const sendTestNotification = () => {
} }
.no-data { .no-data {
text-align: center;
padding: 2rem; padding: 2rem;
text-align: center;
opacity: 0.7; opacity: 0.7;
} }
...@@ -388,28 +406,27 @@ const sendTestNotification = () => { ...@@ -388,28 +406,27 @@ const sendTestNotification = () => {
} }
.actions { .actions {
margin-top: 1.5rem;
display: flex; display: flex;
gap: 1rem; gap: 1rem;
justify-content: center; justify-content: center;
margin-top: 1.5rem;
} }
.btn-action { .btn-action {
padding: 0.75rem 1.5rem; padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(33 150 243 / 80%);
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease; transition: all 0.3s ease;
background: rgba(33, 150, 243, 0.8);
color: white;
font-size: 1rem;
} }
.btn-action:hover { .btn-action:hover {
background: rgba(33, 150, 243, 1); background: rgb(33 150 243 / 100%);
box-shadow: 0 5px 15px rgb(33 150 243 / 30%);
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(33, 150, 243, 0.3);
} }
</style> </style>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/');
};
</script>
<template> <template>
<div class="notfound-view"> <div class="notfound-view">
<div class="content-card"> <div class="content-card">
...@@ -9,70 +19,58 @@ ...@@ -9,70 +19,58 @@
</div> </div>
</template> </template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/');
};
</script>
<style scoped> <style scoped>
.notfound-view { .notfound-view {
max-width: 600px;
margin: 0 auto;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
max-width: 600px;
min-height: 400px; min-height: 400px;
margin: 0 auto;
} }
.content-card { .content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 3rem; padding: 3rem;
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
text-align: center; text-align: center;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
} }
.error-code { .error-code {
margin-bottom: 1rem;
font-size: 6rem; font-size: 6rem;
font-weight: 700; font-weight: 700;
margin-bottom: 1rem; background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%));
background: linear-gradient(45deg, #fff, rgba(255, 255, 255, 0.6));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text; background-clip: text;
-webkit-text-fill-color: transparent;
} }
.content-card h1 { .content-card h1 {
margin: 0 0 1rem 0; margin: 0 0 1rem;
font-size: 2rem; font-size: 2rem;
} }
.content-card p { .content-card p {
margin: 0 0 2rem 0; margin: 0 0 2rem;
opacity: 0.9; opacity: 0.9;
} }
.btn-home { .btn-home {
padding: 0.75rem 2rem; padding: 0.75rem 2rem;
background: rgba(76, 175, 80, 0.8); font-size: 1rem;
font-weight: 600;
color: white; color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
font-size: 1rem;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-home:hover { .btn-home:hover {
background: rgba(76, 175, 80, 1); background: rgb(76 175 80 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
</style> </style>
<script setup lang="ts">
import { reactive } from 'vue';
interface Settings {
theme: string;
darkMode: boolean;
notifications: {
desktop: boolean;
email: boolean;
sms: boolean;
};
language: string;
timezone: string;
security: {
sessionTimeout: number;
twoFactor: boolean;
};
}
const defaultSettings: Settings = {
theme: 'purple',
darkMode: false,
notifications: {
desktop: true,
email: true,
sms: false,
},
language: 'zh-CN',
timezone: 'Asia/Shanghai',
security: {
twoFactor: false,
sessionTimeout: 30,
},
};
const settings = reactive<Settings>({ ...defaultSettings });
const saveSettings = () => {
console.log('保存设置:', settings);
alert('设置已保存!');
};
const resetSettings = () => {
if (confirm('确定要重置为默认设置吗?')) {
Object.assign(settings, defaultSettings);
alert('已重置为默认设置!');
}
};
</script>
<template> <template>
<div class="settings-view"> <div class="settings-view">
<div class="content-card"> <div class="content-card">
...@@ -109,56 +159,6 @@ ...@@ -109,56 +159,6 @@
</div> </div>
</template> </template>
<script setup lang="ts">
import { reactive } from 'vue';
interface Settings {
theme: string;
darkMode: boolean;
notifications: {
desktop: boolean;
email: boolean;
sms: boolean;
};
language: string;
timezone: string;
security: {
twoFactor: boolean;
sessionTimeout: number;
};
}
const defaultSettings: Settings = {
theme: 'purple',
darkMode: false,
notifications: {
desktop: true,
email: true,
sms: false,
},
language: 'zh-CN',
timezone: 'Asia/Shanghai',
security: {
twoFactor: false,
sessionTimeout: 30,
},
};
const settings = reactive<Settings>({ ...defaultSettings });
const saveSettings = () => {
console.log('保存设置:', settings);
alert('设置已保存!');
};
const resetSettings = () => {
if (confirm('确定要重置为默认设置吗?')) {
Object.assign(settings, defaultSettings);
alert('已重置为默认设置!');
}
};
</script>
<style scoped> <style scoped>
.settings-view { .settings-view {
max-width: 1200px; max-width: 1200px;
...@@ -166,15 +166,15 @@ const resetSettings = () => { ...@@ -166,15 +166,15 @@ const resetSettings = () => {
} }
.content-card { .content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem; padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);
} }
.content-card h1 { .content-card h1 {
margin: 0 0 2rem 0; margin: 0 0 2rem;
font-size: 2rem; font-size: 2rem;
} }
...@@ -186,22 +186,22 @@ const resetSettings = () => { ...@@ -186,22 +186,22 @@ const resetSettings = () => {
} }
.setting-group { .setting-group {
background: rgba(255, 255, 255, 0.05);
padding: 1.5rem; padding: 1.5rem;
background: rgb(255 255 255 / 5%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem; border-radius: 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.1);
} }
.setting-group h2 { .setting-group h2 {
margin: 0 0 1rem 0; margin: 0 0 1rem;
font-size: 1.2rem; font-size: 1.2rem;
color: rgba(255, 255, 255, 0.95); color: rgb(255 255 255 / 95%);
} }
.setting-item { .setting-item {
display: flex; display: flex;
justify-content: space-between;
align-items: center; align-items: center;
justify-content: space-between;
margin-bottom: 1rem; margin-bottom: 1rem;
} }
...@@ -212,11 +212,11 @@ const resetSettings = () => { ...@@ -212,11 +212,11 @@ const resetSettings = () => {
.select-input, .select-input,
.number-input { .number-input {
padding: 0.5rem; padding: 0.5rem;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 0.5rem;
color: white;
font-size: 0.9rem; font-size: 0.9rem;
color: white;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 0.5rem;
} }
.number-input { .number-input {
...@@ -238,52 +238,51 @@ const resetSettings = () => { ...@@ -238,52 +238,51 @@ const resetSettings = () => {
.btn-save, .btn-save,
.btn-reset { .btn-reset {
padding: 0.75rem 2rem; padding: 0.75rem 2rem;
font-weight: 600;
cursor: pointer;
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-save { .btn-save {
background: rgba(76, 175, 80, 0.8);
color: white; color: white;
background: rgb(76 175 80 / 80%);
} }
.btn-save:hover { .btn-save:hover {
background: rgba(76, 175, 80, 1); background: rgb(76 175 80 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
.btn-reset { .btn-reset {
background: rgba(158, 158, 158, 0.8);
color: white; color: white;
background: rgb(158 158 158 / 80%);
} }
.btn-reset:hover { .btn-reset:hover {
background: rgba(158, 158, 158, 1); background: rgb(158 158 158 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
.current-settings { .current-settings {
background: rgba(0, 0, 0, 0.3);
padding: 1.5rem; padding: 1.5rem;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem; border-radius: 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.1);
} }
.current-settings h3 { .current-settings h3 {
margin: 0 0 1rem 0; margin: 0 0 1rem;
font-size: 1.1rem; font-size: 1.1rem;
} }
.current-settings pre { .current-settings pre {
margin: 0; margin: 0;
overflow-x: auto;
font-family: 'Courier New', monospace; font-family: 'Courier New', monospace;
font-size: 0.9rem; font-size: 0.9rem;
line-height: 1.6; line-height: 1.6;
color: #a8e6cf; color: #a8e6cf;
overflow-x: auto;
} }
</style> </style>
<template>
<div class="user-view">
<div class="content-card">
<h1>👥 用户管理</h1>
<div class="toolbar">
<button @click="addUser" class="btn-add">➕ 新增用户</button>
</div>
<div class="table-container">
<table class="user-table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<span class="badge" :class="`badge-${user.role}`">
{{ user.role }}
</span>
</td>
<td>
<span class="status" :class="user.active ? 'status-active' : 'status-inactive'">
{{ user.active ? '在线' : '离线' }}
</span>
</td>
<td>
<button @click="editUser(user)" class="btn-edit">编辑</button>
<button @click="deleteUser(user.id)" class="btn-delete">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { ref } from 'vue';
...@@ -53,7 +5,7 @@ interface User { ...@@ -53,7 +5,7 @@ interface User {
id: number; id: number;
name: string; name: string;
email: string; email: string;
role: 'admin' | 'user' | 'guest'; role: 'admin' | 'guest' | 'user';
active: boolean; active: boolean;
} }
...@@ -105,15 +57,69 @@ const editUser = (user: User) => { ...@@ -105,15 +57,69 @@ const editUser = (user: User) => {
}; };
const deleteUser = (id: number) => { const deleteUser = (id: number) => {
const index = users.value.findIndex(u => u.id === id); const index = users.value.findIndex((u) => u.id === id);
if (index > -1) { if (
if (confirm(`确定要删除用户 ${users.value[index].name} 吗?`)) { index !== -1 &&
users.value.splice(index, 1); confirm(`确定要删除用户 ${users.value[index].name} 吗?`)
} ) {
users.value.splice(index, 1);
} }
}; };
</script> </script>
<template>
<div class="user-view">
<div class="content-card">
<h1>👥 用户管理</h1>
<div class="toolbar">
<button @click="addUser" class="btn-add">➕ 新增用户</button>
</div>
<div class="table-container">
<table class="user-table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<span class="badge" :class="`badge-${user.role}`">
{{ user.role }}
</span>
</td>
<td>
<span
class="status"
:class="user.active ? 'status-active' : 'status-inactive'"
>
{{ user.active ? '在线' : '离线' }}
</span>
</td>
<td>
<button @click="editUser(user)" class="btn-edit">编辑</button>
<button @click="deleteUser(user.id)" class="btn-delete">
删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<style scoped> <style scoped>
.user-view { .user-view {
max-width: 1200px; max-width: 1200px;
...@@ -121,15 +127,15 @@ const deleteUser = (id: number) => { ...@@ -121,15 +127,15 @@ const deleteUser = (id: number) => {
} }
.content-card { .content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem; padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);
} }
.content-card h1 { .content-card h1 {
margin: 0 0 1.5rem 0; margin: 0 0 1.5rem;
font-size: 2rem; font-size: 2rem;
} }
...@@ -139,17 +145,17 @@ const deleteUser = (id: number) => { ...@@ -139,17 +145,17 @@ const deleteUser = (id: number) => {
.btn-add { .btn-add {
padding: 0.75rem 1.5rem; padding: 0.75rem 1.5rem;
background: rgba(76, 175, 80, 0.8); font-weight: 600;
color: white; color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-add:hover { .btn-add:hover {
background: rgba(76, 175, 80, 1); background: rgb(76 175 80 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
...@@ -163,19 +169,19 @@ const deleteUser = (id: number) => { ...@@ -163,19 +169,19 @@ const deleteUser = (id: number) => {
} }
.user-table thead { .user-table thead {
background: rgba(255, 255, 255, 0.1); background: rgb(255 255 255 / 10%);
} }
.user-table th, .user-table th,
.user-table td { .user-table td {
padding: 1rem; padding: 1rem;
text-align: left; text-align: left;
border-bottom: 1px solid rgba(255, 255, 255, 0.1); border-bottom: 1px solid rgb(255 255 255 / 10%);
} }
.user-table th { .user-table th {
font-weight: 600; font-weight: 600;
color: rgba(255, 255, 255, 0.95); color: rgb(255 255 255 / 95%);
} }
.user-table tbody tr { .user-table tbody tr {
...@@ -183,70 +189,69 @@ const deleteUser = (id: number) => { ...@@ -183,70 +189,69 @@ const deleteUser = (id: number) => {
} }
.user-table tbody tr:hover { .user-table tbody tr:hover {
background: rgba(255, 255, 255, 0.05); background: rgb(255 255 255 / 5%);
} }
.badge { .badge {
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 600; font-weight: 600;
border-radius: 1rem;
} }
.badge-admin { .badge-admin {
background: rgba(244, 67, 54, 0.8); background: rgb(244 67 54 / 80%);
} }
.badge-user { .badge-user {
background: rgba(33, 150, 243, 0.8); background: rgb(33 150 243 / 80%);
} }
.badge-guest { .badge-guest {
background: rgba(158, 158, 158, 0.8); background: rgb(158 158 158 / 80%);
} }
.status { .status {
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 600; font-weight: 600;
border-radius: 1rem;
} }
.status-active { .status-active {
background: rgba(76, 175, 80, 0.8); background: rgb(76 175 80 / 80%);
} }
.status-inactive { .status-inactive {
background: rgba(158, 158, 158, 0.8); background: rgb(158 158 158 / 80%);
} }
.btn-edit, .btn-edit,
.btn-delete { .btn-delete {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
margin-right: 0.5rem; margin-right: 0.5rem;
font-weight: 600;
cursor: pointer;
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-edit { .btn-edit {
background: rgba(33, 150, 243, 0.8);
color: white; color: white;
background: rgb(33 150 243 / 80%);
} }
.btn-edit:hover { .btn-edit:hover {
background: rgba(33, 150, 243, 1); background: rgb(33 150 243 / 100%);
} }
.btn-delete { .btn-delete {
background: rgba(244, 67, 54, 0.8);
color: white; color: white;
background: rgb(244 67 54 / 80%);
} }
.btn-delete:hover { .btn-delete:hover {
background: rgba(244, 67, 54, 1); background: rgb(244 67 54 / 100%);
} }
</style> </style>
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2020", "target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true, "useDefineForClassFields": true,
/* Path Alias */
"baseUrl": ".",
"module": "ESNext", "module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */ /* Bundler mode */
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowImportingTsExtensions": true, "paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "allowImportingTsExtensions": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */ /* Linting */
"strict": true, "strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true, "noEmit": true,
"isolatedModules": true,
/* Path Alias */ "skipLibCheck": true
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}, },
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }],
"references": [{ "path": "./tsconfig.node.json" }] "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
} }
{ {
"compilerOptions": { "compilerOptions": {
"composite": true, "composite": true,
"skipLibCheck": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowSyntheticDefaultImports": true "allowSyntheticDefaultImports": true,
"skipLibCheck": true
}, },
"include": ["vite.config.ts"] "include": ["vite.config.ts"]
} }
import { defineConfig } from 'vite'; import { resolve } from 'node:path';
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx'; import vueJsx from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite'; import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite'; import Components from 'unplugin-vue-components/vite';
import { defineConfig } from 'vite';
import qiankun from 'vite-plugin-qiankun'; import qiankun from 'vite-plugin-qiankun';
const PORT = 8081; const PORT = 8081;
...@@ -12,59 +13,58 @@ const APP_NAME = 'subapp-vue'; // 与基座配置的 name 一致 ...@@ -12,59 +13,58 @@ const APP_NAME = 'subapp-vue'; // 与基座配置的 name 一致
export default defineConfig(({ mode, command }) => { export default defineConfig(({ mode, command }) => {
const isDev = mode === 'development'; const isDev = mode === 'development';
const isServe = command === 'serve'; const isServe = command === 'serve';
return { return {
base: isDev && isServe ? `http://localhost:${PORT}/` : `/${APP_NAME}/`, // 生产环境使用应用名作为基础路径 base: isDev && isServe ? `http://localhost:${PORT}/` : `/${APP_NAME}/`, // 生产环境使用应用名作为基础路径
plugins: [ plugins: [
vue(), vue(),
vueJsx(), vueJsx(),
// 自动导入 Vue 相关函数 // 自动导入 Vue 相关函数
AutoImport({ AutoImport({
imports: ['vue', 'vue-router', 'pinia'], imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts', dts: 'src/auto-imports.d.ts',
eslintrc: { eslintrc: {
enabled: false, enabled: false,
},
}),
// 自动导入组件
Components({
dts: 'src/components.d.ts',
}),
// qiankun 插件配置
qiankun(APP_NAME, {
useDevMode: isDev, // 根据实际环境动态设置
}),
],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
}, },
}),
// 自动导入组件
Components({
dts: 'src/components.d.ts',
}),
// qiankun 插件配置
qiankun(APP_NAME, {
useDevMode: isDev, // 根据实际环境动态设置
}),
],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
}, },
}, server: {
server: { port: PORT,
port: PORT, cors: true, // 允许跨域
cors: true, // 允许跨域 host: true,
host: true, origin: `http://localhost:${PORT}`, // 设置资源加载的 origin
origin: `http://localhost:${PORT}`, // 设置资源加载的 origin headers: {
headers: { 'Access-Control-Allow-Origin': '*', // 允许所有来源
'Access-Control-Allow-Origin': '*', // 允许所有来源 },
}, },
}, build: {
build: { target: 'esnext',
target: 'esnext', minify: false, // 开发环境不压缩,便于调试
minify: false, // 开发环境不压缩,便于调试 cssCodeSplit: false, // css 不拆分
cssCodeSplit: false, // css 不拆分 rollupOptions: {
rollupOptions: { output: {
output: { // qiankun 需要的输出格式
// qiankun 需要的输出格式 format: 'umd',
format: 'umd', // UMD 库名称,必须与应用名称一致
// UMD 库名称,必须与应用名称一致 name: `qiankunApp_${APP_NAME.replaceAll('-', '_')}`,
name: `qiankunApp_${APP_NAME.replace(/-/g, '_')}`, entryFileNames: 'assets/[name].js',
entryFileNames: 'assets/[name].js', chunkFileNames: 'assets/[name].[hash].js',
chunkFileNames: 'assets/[name].[hash].js', assetFileNames: 'assets/[name].[hash].[ext]',
assetFileNames: 'assets/[name].[hash].[ext]', },
}, },
}, },
},
}; };
}); });
import { defineConfig } from 'vitepress' import { defineConfig } from 'vitepress';
// https://vitepress.dev/reference/site-config // https://vitepress.dev/reference/site-config
export default defineConfig({ export default defineConfig({
title: "Venus Admin", title: 'Venus Admin',
description: "现代化的 Vue3 中后台管理系统框架", description: '现代化的 Vue3 中后台管理系统框架',
lang: 'zh-CN', lang: 'zh-CN',
// 主题配置 // 主题配置
themeConfig: { themeConfig: {
// https://vitepress.dev/reference/default-theme-config // https://vitepress.dev/reference/default-theme-config
logo: '/logo.svg', logo: '/logo.svg',
nav: [ nav: [
{ text: '首页', link: '/' }, { text: '首页', link: '/' },
{ text: '指南', link: '/guide/introduction' }, { text: '指南', link: '/guide/introduction' },
...@@ -19,10 +19,13 @@ export default defineConfig({ ...@@ -19,10 +19,13 @@ export default defineConfig({
{ {
text: '相关链接', text: '相关链接',
items: [ items: [
{ text: 'GitHub', link: 'https://github.com/venusjs/vue-venus-admin' }, {
{ text: '更新日志', link: '/changelog' } text: 'GitHub',
] link: 'https://github.com/venusjs/vue-venus-admin',
} },
{ text: '更新日志', link: '/changelog' },
],
},
], ],
sidebar: { sidebar: {
...@@ -33,7 +36,7 @@ export default defineConfig({ ...@@ -33,7 +36,7 @@ export default defineConfig({
{ text: '简介', link: '/guide/introduction' }, { text: '简介', link: '/guide/introduction' },
{ text: '快速开始', link: '/guide/quick-start' }, { text: '快速开始', link: '/guide/quick-start' },
{ text: '项目配置', link: '/guide/configuration' }, { text: '项目配置', link: '/guide/configuration' },
] ],
}, },
{ {
text: '基础', text: '基础',
...@@ -42,7 +45,7 @@ export default defineConfig({ ...@@ -42,7 +45,7 @@ export default defineConfig({
{ text: '路由和菜单', link: '/guide/router-menu' }, { text: '路由和菜单', link: '/guide/router-menu' },
{ text: '权限管理', link: '/guide/permission' }, { text: '权限管理', link: '/guide/permission' },
{ text: '状态管理', link: '/guide/state-management' }, { text: '状态管理', link: '/guide/state-management' },
] ],
}, },
{ {
text: '进阶', text: '进阶',
...@@ -51,8 +54,8 @@ export default defineConfig({ ...@@ -51,8 +54,8 @@ export default defineConfig({
{ text: '国际化', link: '/guide/i18n' }, { text: '国际化', link: '/guide/i18n' },
{ text: '构建和部署', link: '/guide/build-deploy' }, { text: '构建和部署', link: '/guide/build-deploy' },
{ text: '环境变量', link: '/guide/env-variables' }, { text: '环境变量', link: '/guide/env-variables' },
] ],
} },
], ],
'/components/': [ '/components/': [
{ {
...@@ -63,8 +66,8 @@ export default defineConfig({ ...@@ -63,8 +66,8 @@ export default defineConfig({
{ text: '表格组件', link: '/components/table' }, { text: '表格组件', link: '/components/table' },
{ text: '弹窗组件', link: '/components/modal' }, { text: '弹窗组件', link: '/components/modal' },
{ text: '图表组件', link: '/components/chart' }, { text: '图表组件', link: '/components/chart' },
] ],
} },
], ],
'/api/': [ '/api/': [
{ {
...@@ -73,13 +76,13 @@ export default defineConfig({ ...@@ -73,13 +76,13 @@ export default defineConfig({
{ text: '核心 API', link: '/api/core' }, { text: '核心 API', link: '/api/core' },
{ text: '工具函数', link: '/api/utils' }, { text: '工具函数', link: '/api/utils' },
{ text: '类型定义', link: '/api/types' }, { text: '类型定义', link: '/api/types' },
] ],
} },
] ],
}, },
socialLinks: [ socialLinks: [
{ icon: 'github', link: 'https://github.com/venusjs/vue-venus-admin' } { icon: 'github', link: 'https://github.com/venusjs/vue-venus-admin' },
], ],
// 搜索配置 // 搜索配置
...@@ -91,44 +94,45 @@ export default defineConfig({ ...@@ -91,44 +94,45 @@ export default defineConfig({
translations: { translations: {
button: { button: {
buttonText: '搜索文档', buttonText: '搜索文档',
buttonAriaLabel: '搜索文档' buttonAriaLabel: '搜索文档',
}, },
modal: { modal: {
noResultsText: '无法找到相关结果', noResultsText: '无法找到相关结果',
resetButtonTitle: '清除查询条件', resetButtonTitle: '清除查询条件',
footer: { footer: {
selectText: '选择', selectText: '选择',
navigateText: '切换' navigateText: '切换',
} },
} },
} },
} },
} },
} },
}, },
// 编辑链接 // 编辑链接
editLink: { editLink: {
pattern: 'https://github.com/venusjs/vue-venus-admin/edit/main/docs/:path', pattern:
text: '在 GitHub 上编辑此页' 'https://github.com/venusjs/vue-venus-admin/edit/main/docs/:path',
text: '在 GitHub 上编辑此页',
}, },
// 页脚 // 页脚
footer: { footer: {
message: '基于 MIT 许可发布', message: '基于 MIT 许可发布',
copyright: 'Copyright © 2024-present Venus Admin' copyright: 'Copyright © 2024-present Venus Admin',
}, },
// 大纲配置 // 大纲配置
outline: { outline: {
level: [2, 3], level: [2, 3],
label: '页面导航' label: '页面导航',
}, },
// 文档页脚 // 文档页脚
docFooter: { docFooter: {
prev: '上一页', prev: '上一页',
next: '下一页' next: '下一页',
}, },
// 最后更新时间 // 最后更新时间
...@@ -136,8 +140,8 @@ export default defineConfig({ ...@@ -136,8 +140,8 @@ export default defineConfig({
text: '最后更新于', text: '最后更新于',
formatOptions: { formatOptions: {
dateStyle: 'short', dateStyle: 'short',
timeStyle: 'short' timeStyle: 'short',
} },
}, },
// 返回顶部 // 返回顶部
...@@ -145,16 +149,16 @@ export default defineConfig({ ...@@ -145,16 +149,16 @@ export default defineConfig({
sidebarMenuLabel: '菜单', sidebarMenuLabel: '菜单',
darkModeSwitchLabel: '主题', darkModeSwitchLabel: '主题',
lightModeSwitchTitle: '切换到浅色模式', lightModeSwitchTitle: '切换到浅色模式',
darkModeSwitchTitle: '切换到深色模式' darkModeSwitchTitle: '切换到深色模式',
}, },
// Markdown 配置 // Markdown 配置
markdown: { markdown: {
theme: { theme: {
light: 'github-light', light: 'github-light',
dark: 'github-dark' dark: 'github-dark',
}, },
lineNumbers: true lineNumbers: true,
}, },
// 构建配置 // 构建配置
...@@ -167,7 +171,6 @@ export default defineConfig({ ...@@ -167,7 +171,6 @@ export default defineConfig({
['link', { rel: 'icon', href: '/favicon.ico' }], ['link', { rel: 'icon', href: '/favicon.ico' }],
['meta', { name: 'theme-color', content: '#646cff' }], ['meta', { name: 'theme-color', content: '#646cff' }],
['meta', { name: 'og:type', content: 'website' }], ['meta', { name: 'og:type', content: 'website' }],
['meta', { name: 'og:locale', content: 'zh-CN' }] ['meta', { name: 'og:locale', content: 'zh-CN' }],
] ],
}) });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!