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">
<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)
Venus
<div align="center">
<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)
Venus
/// <reference types="vite/client" />
// / <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
......@@ -10,26 +10,25 @@
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "catalog:",
"vue-router": "catalog:",
"pinia": "catalog:",
"qiankun": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"axios": "catalog:",
"@element-plus/icons-vue": "catalog:",
"element-plus": "catalog:",
"@venus/common-ui": "workspace:*"
"pinia": "catalog:",
"qiankun": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"@types/node": "catalog:"
"vue-tsc": "catalog:"
}
}
<script setup lang="ts">
// 根组件入口
</script>
<template>
<div id="main-app">
<router-view />
</div>
</template>
<script setup lang="ts">
// 根组件入口
</script>
<style scoped>
#main-app {
width: 100%;
......@@ -15,4 +15,3 @@
min-height: 100vh;
}
</style>
......@@ -3,4 +3,3 @@
*/
export * from './user';
......@@ -9,7 +9,7 @@ import type { LoginParams, LoginResponse, UserInfo } from '@/types/user';
* 模拟延迟
*/
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 = [
/**
* 模拟登录
*/
export const mockLogin = async (data: LoginParams): Promise<ApiResponse<LoginResponse>> => {
export const mockLogin = async (
data: LoginParams,
): Promise<ApiResponse<LoginResponse>> => {
await mockDelay(800);
const user = mockUsers.find(u => u.username === data.username);
const user = mockUsers.find((u) => u.username === data.username);
if (!user) {
return {
......@@ -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);
// 从 token 中解析用户名
const username = token.split('_')[2];
const user = mockUsers.find(u => u.username === username);
const user = mockUsers.find((u) => u.username === username);
if (!user) {
return {
......@@ -187,4 +191,3 @@ export const getUserInfo = () => {
`;
console.log(MOCK_API_USAGE);
......@@ -2,21 +2,22 @@
* 用户相关 API
*/
import { post, get } from '@/utils/request';
import type { ApiResponse } from '@/types/api';
import type {
LoginParams,
LoginResponse,
UserInfo,
import type {
ChangePasswordParams,
UpdateUserInfoParams
LoginParams,
LoginResponse,
UpdateUserInfoParams,
UserInfo,
} from '@/types/user';
import { getToken } from '@/utils/auth';
import { get, post } from '@/utils/request';
// ==================== 开发环境使用模拟 API ====================
// 取消下面的注释以使用模拟 API 进行开发测试
// 测试账号:admin/123456, user/123456, guest/123456
import { mockLogin, mockLogout, mockGetUserInfo } from './mock';
import { getToken } from '@/utils/auth';
import { mockGetUserInfo, mockLogin, mockLogout } from './mock';
const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false
......@@ -55,9 +56,12 @@ export const getUserInfo = () => {
* 刷新 Token
*/
export const refreshToken = (refreshToken: string) => {
return post<ApiResponse<{ token: string; refreshToken: string }>>('/auth/refresh', {
refreshToken,
});
return post<ApiResponse<{ refreshToken: string; token: string }>>(
'/auth/refresh',
{
refreshToken,
},
);
};
/**
......@@ -80,4 +84,3 @@ export const updateUserInfo = (data: UpdateUserInfoParams) => {
export const getCaptcha = () => {
return get<ApiResponse<{ captcha: string; key: string }>>('/auth/captcha');
};
<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', `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>
<script setup lang="ts">
import type { GlobalState } from '../qiankun';
<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>
import { computed, onMounted, onUnmounted, ref } from 'vue';
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { communicationManager, type GlobalState } from '../qiankun';
import { communicationManager } from '../qiankun';
// 显示面板
const showPanel = ref(false);
......@@ -81,10 +34,10 @@ const getIcon = (type: string) => {
const formatTime = (timestamp: number) => {
const now = Date.now();
const diff = now - timestamp;
if (diff < 60000) return '刚刚';
if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
if (diff < 60_000) return '刚刚';
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}分钟前`;
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}小时前`;
return new Date(timestamp).toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
......@@ -125,6 +78,68 @@ onUnmounted(() => {
});
</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>
.notification-center {
position: relative;
......@@ -132,18 +147,18 @@ onUnmounted(() => {
.notification-badge {
position: relative;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
cursor: pointer;
border-radius: 50%;
transition: background-color 0.2s;
}
.notification-badge:hover {
background-color: rgba(0, 0, 0, 0.05);
background-color: rgb(0 0 0 / 5%);
}
.notification-badge .icon {
......@@ -154,38 +169,38 @@ onUnmounted(() => {
position: absolute;
top: 4px;
right: 4px;
display: flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 4px;
background-color: #ff4d4f;
color: white;
font-size: 12px;
color: white;
background-color: #ff4d4f;
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
}
.notification-panel {
position: absolute;
top: 50px;
right: 0;
z-index: 1000;
display: flex;
flex-direction: column;
width: 400px;
max-height: 600px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
z-index: 1000;
box-shadow: 0 4px 20px rgb(0 0 0 / 15%);
}
.panel-header {
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
}
.panel-header h3 {
......@@ -196,11 +211,11 @@ onUnmounted(() => {
.clear-btn {
padding: 4px 12px;
font-size: 14px;
cursor: pointer;
background: transparent;
border: 1px solid #d9d9d9;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
......@@ -210,15 +225,15 @@ onUnmounted(() => {
}
.notification-list {
overflow-y: auto;
max-height: 500px;
overflow-y: auto;
}
.notification-item {
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
display: flex;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid #f0f0f0;
transition: background-color 0.2s;
}
......@@ -227,8 +242,8 @@ onUnmounted(() => {
}
.notification-icon {
font-size: 24px;
flex-shrink: 0;
font-size: 24px;
}
.notification-content {
......@@ -237,17 +252,17 @@ onUnmounted(() => {
}
.notification-title {
font-weight: 600;
font-size: 14px;
margin-bottom: 4px;
font-size: 14px;
font-weight: 600;
color: #262626;
}
.notification-message {
font-size: 14px;
color: #595959;
margin-bottom: 8px;
font-size: 14px;
line-height: 1.5;
color: #595959;
}
.notification-meta {
......@@ -258,21 +273,21 @@ onUnmounted(() => {
}
.close-btn {
flex-shrink: 0;
width: 24px;
height: 24px;
flex-shrink: 0;
border: none;
background: transparent;
cursor: pointer;
font-size: 16px;
color: #8c8c8c;
cursor: pointer;
background: transparent;
border: none;
border-radius: 4px;
transition: all 0.2s;
}
.close-btn:hover {
background-color: rgba(0, 0, 0, 0.06);
color: #262626;
background-color: rgb(0 0 0 / 6%);
}
.empty-state {
......@@ -281,13 +296,13 @@ onUnmounted(() => {
}
.empty-icon {
font-size: 48px;
margin-bottom: 12px;
font-size: 48px;
}
.empty-text {
color: #8c8c8c;
font-size: 14px;
color: #8c8c8c;
}
/* 不同类型的通知样式 */
......@@ -323,4 +338,3 @@ onUnmounted(() => {
transform: translateY(-10px);
}
</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">
import { computed } from 'vue';
import type { MenuItem } from '@/types/menu';
import { computed } from 'vue';
import SidebarMenuItem from './SidebarMenuItem.vue';
interface Props {
......@@ -73,8 +29,10 @@ const isExpanded = computed(() => {
// 是否激活(当前路由或子路由激活)
const isActive = computed(() => {
return props.activePath === props.menu.path ||
props.activePath.startsWith(props.menu.path + '/');
return (
props.activePath === props.menu.path ||
props.activePath.startsWith(`${props.menu.path}/`)
);
});
// 点击菜单项
......@@ -92,21 +50,67 @@ const handleToggle = () => {
};
</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>
.sidebar-menu-item {
width: 100%;
}
.menu-item-content {
position: relative;
display: flex;
align-items: center;
gap: 8px;
align-items: center;
padding: 10px 16px;
color: #333;
cursor: pointer;
transition: all 0.3s;
position: relative;
user-select: none;
transition: all 0.3s;
}
/* 层级缩进 */
......@@ -125,46 +129,46 @@ const handleToggle = () => {
}
.menu-item-content:hover {
background-color: #f5f5f5;
color: #1890ff;
background-color: #f5f5f5;
}
.menu-item-content.active {
background-color: #e6f7ff;
color: #1890ff;
font-weight: 500;
color: #1890ff;
background-color: #e6f7ff;
}
.menu-item-content.active::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
left: 0;
width: 3px;
content: '';
background-color: #1890ff;
}
.expand-icon {
flex-shrink: 0;
width: 16px;
height: 16px;
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
font-size: 10px;
color: #666;
transition: transform 0.3s;
}
.menu-icon {
flex-shrink: 0;
font-size: 16px;
width: 20px;
height: 20px;
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
font-size: 16px;
}
.menu-title {
......@@ -176,15 +180,15 @@ const handleToggle = () => {
.menu-badge {
flex-shrink: 0;
padding: 0 6px;
min-width: 18px;
height: 18px;
line-height: 18px;
padding: 0 6px;
font-size: 11px;
line-height: 18px;
color: #fff;
text-align: center;
background-color: #ff4d4f;
border-radius: 9px;
min-width: 18px;
text-align: center;
}
.submenu {
......@@ -199,15 +203,15 @@ const handleToggle = () => {
.submenu-expand-enter-from,
.submenu-expand-leave-to {
opacity: 0;
max-height: 0;
opacity: 0;
transform: translateY(-10px);
}
.submenu-expand-enter-to,
.submenu-expand-leave-from {
opacity: 1;
max-height: 1000px;
opacity: 1;
transform: translateY(0);
}
......@@ -218,7 +222,7 @@ const handleToggle = () => {
/* 二级菜单样式 */
.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 {
......@@ -227,11 +231,10 @@ const handleToggle = () => {
/* 三级菜单样式 */
.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 {
background-color: #ebebeb;
}
</style>
......@@ -13,7 +13,7 @@ export const homeMenus: MenuItem[] = [
path: '/home/dashboard',
icon: '📊',
level: 1,
}
},
];
// Vue 微应用侧边栏菜单(多级示例)
......@@ -49,16 +49,15 @@ export const vueAppMenus: MenuItem[] = [
path: '/subapp-vue/user',
icon: '🎯',
level: 1,
children: [
],
},{
children: [],
},
{
id: 'marketing',
title: '系统管理',
path: '/subapp-vue/settings',
icon: '🎯',
level: 1,
children: [
],
children: [],
},
];
......@@ -166,7 +165,7 @@ export const topMenus: TopMenuItem[] = [
* 根据路径获取对应的侧边栏菜单
*/
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 || [];
}
......@@ -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[] = [];
function findPath(items: MenuItem[], target: string, currentPaths: string[]): boolean {
function findPath(
items: MenuItem[],
target: string,
currentPaths: string[],
): boolean {
for (const item of items) {
const newPaths = [...currentPaths, item.path];
if (item.path === target) {
paths.push(...newPaths);
return true;
}
if (item.children && findPath(item.children, target, newPaths)) {
return true;
}
}
return false;
}
findPath(menus, targetPath, []);
return paths;
}
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import { setupQiankun } from './qiankun';
import { useUserStore, useAppStore } from './stores';
import router from './router';
import { useAppStore, useUserStore } from './stores';
import { getToken } from './utils/auth';
import './style.css';
// 创建应用实例
......@@ -31,12 +34,12 @@ async function initApp() {
if (token) {
const userStore = useUserStore();
userStore.setTokenValue(token);
// 尝试获取用户信息(如果失败,路由守卫会处理)
try {
await userStore.getUserInfo();
console.log('[基座] 用户信息恢复成功,已同步到 qiankun 全局状态');
} catch (error) {
} catch {
console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
}
}
......@@ -51,14 +54,14 @@ async function initApp() {
function setupStoreSync() {
const userStore = useUserStore();
const appStore = useAppStore();
// 监听用户信息变化
userStore.$subscribe(() => {
console.log('[基座] 用户 Store 变化,同步到 qiankun 全局状态');
// 每次 Store 变化时,同步用户信息
userStore.syncUserToQiankun();
});
// 监听主题变化,同步到 qiankun 全局状态
appStore.$subscribe((_mutation, state) => {
import('./qiankun/communication').then(({ communicationManager }) => {
......@@ -85,4 +88,3 @@ initApp().then(() => {
setupQiankun();
});
});
......@@ -32,18 +32,18 @@ export const microApps: MicroAppConfig[] = [
*/
function getAppEntry(appName: string, defaultEntry: string): string {
const env = (import.meta as any).env?.MODE || 'development';
// 开发环境使用默认地址
if (env === 'development') {
return defaultEntry;
}
// 优先使用环境变量配置的基础地址
const baseUrl = (import.meta as any).env?.VITE_MICRO_APP_BASE_URL;
if (baseUrl) {
return `${baseUrl}/${appName}`;
}
// 如果未配置环境变量,使用当前域名的相对路径(同域部署)
// 例如:https://your-domain.com/subapp-vue
return `${window.location.origin}/${appName}`;
......@@ -84,4 +84,3 @@ export function getMicroAppByPath(path: string): MicroAppConfig | undefined {
export function isMicroAppRegistered(name: string): boolean {
return microApps.some((app) => app.name === name);
}
......@@ -6,23 +6,23 @@ import { initGlobalState, MicroAppStateActions } from 'qiankun';
*/
export interface GlobalState {
// 用户信息
user: {
user: null | {
avatar: string;
id: string;
name: string;
avatar: string;
role: string;
permissions: string[];
} | null;
role: string;
};
// 主题配置
theme: {
mode: 'light' | 'dark';
mode: 'dark' | 'light';
primaryColor: string;
};
// 消息通知列表
notifications: Notification[];
// 系统配置
config: {
apiBaseUrl: string;
......@@ -30,14 +30,14 @@ export interface GlobalState {
};
// 当前激活的菜单信息
currentMenu: {
menuId: string;
menuTitle: string;
menuPath: string;
currentMenu: null | {
menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
timestamp: number;
} | null;
};
}
/**
......@@ -45,7 +45,7 @@ export interface GlobalState {
*/
export interface Notification {
id: string;
type: 'success' | 'warning' | 'error' | 'info';
type: 'error' | 'info' | 'success' | 'warning';
title: string;
message: string;
timestamp: number;
......@@ -82,34 +82,37 @@ const initialState: GlobalState = {
class CommunicationManager {
// qiankun 的状态管理实例
private actions: MicroAppStateActions | null = null;
// 当前全局状态的本地副本(qiankun 不提供 getGlobalState 方法,需要自己维护)
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() {
// 初始化 qiankun 的全局状态
this.actions = initGlobalState(initialState);
// 监听状态变化,同步更新本地副本
this.actions.onGlobalStateChange((state, prev) => {
console.log('[基座通信] 全局状态变化:', state, prev);
// 更新本地状态副本
this.currentState = state as GlobalState;
// 触发所有监听器
this.listeners.forEach(listener => {
listener(state as GlobalState, prev as GlobalState);
});
addNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
};
this.setGlobalState({
notifications: [...this.currentState.notifications, newNotification],
});
}
/**
* 清空所有通知
*/
clearNotifications() {
this.setGlobalState({
notifications: [],
});
console.log('[基座通信] 通信管理器初始化完成');
}
/**
......@@ -121,44 +124,26 @@ class CommunicationManager {
}
/**
* 设置全局状态(支持部分更新)
* @param state 要更新的状态
* 初始化全局状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.actions) {
// 深度合并更新本地状态副本(立即更新,避免异步延迟)
this.currentState = this.deepMerge(this.currentState, state);
// 同步到 qiankun 全局状态(只传入变化的部分)
this.actions.setGlobalState(state);
console.log('[基座通信] 全局状态已更新:', state);
} else {
console.warn('[基座通信] 通信管理器未初始化');
}
}
init() {
// 初始化 qiankun 的全局状态
this.actions = initGlobalState(initialState);
/**
* 深度合并对象(简单实现)
*/
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)) {
if (targetValue && typeof targetValue === 'object' && !Array.isArray(targetValue)) {
result[key] = this.deepMerge(targetValue, sourceValue);
} else {
result[key] = sourceValue;
}
} else {
result[key] = sourceValue;
}
}
return result;
// 监听状态变化,同步更新本地副本
this.actions.onGlobalStateChange((state, prev) => {
console.log('[基座通信] 全局状态变化:', state, prev);
// 更新本地状态副本
this.currentState = state as GlobalState;
// 触发所有监听器
this.listeners.forEach((listener) => {
listener(state as GlobalState, prev as GlobalState);
});
});
console.log('[基座通信] 通信管理器初始化完成');
}
/**
......@@ -166,72 +151,45 @@ class CommunicationManager {
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(callback: (state: GlobalState, prev: GlobalState) => void): () => void {
onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback);
// 返回取消监听的函数
return () => {
const index = this.listeners.indexOf(callback);
if (index > -1) {
if (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
*/
removeNotification(id: string) {
this.setGlobalState({
notifications: this.currentState.notifications.filter(n => n.id !== id),
notifications: this.currentState.notifications.filter((n) => n.id !== id),
});
}
/**
* 清空所有通知
* 设置全局状态(支持部分更新)
* @param state 要更新的状态
*/
clearNotifications() {
this.setGlobalState({
notifications: [],
});
setGlobalState(state: Partial<GlobalState>) {
if (this.actions) {
// 深度合并更新本地状态副本(立即更新,避免异步延迟)
this.currentState = this.deepMerge(this.currentState, state);
// 同步到 qiankun 全局状态(只传入变化的部分)
this.actions.setGlobalState(state);
console.log('[基座通信] 全局状态已更新:', state);
} else {
console.warn('[基座通信] 通信管理器未初始化');
}
}
/**
......@@ -252,11 +210,11 @@ class CommunicationManager {
* @param menu 菜单信息
*/
updateCurrentMenu(menu: {
menuId: string;
menuTitle: string;
menuPath: string;
menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
}) {
this.setGlobalState({
currentMenu: {
......@@ -266,6 +224,56 @@ class CommunicationManager {
});
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();
export function broadcast(
type: Notification['type'],
title: string,
message: string
message: string,
) {
communicationManager.addNotification({
type,
......@@ -289,4 +297,3 @@ export function broadcast(
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">
import { ref, onMounted, onUnmounted } from 'vue';
import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { getMicroAppByPath } from '../apps';
const route = useRoute();
const loading = ref(true);
const error = ref('');
let timer: number | null = null;
let timer: null | number = null;
/**
* 初始化微应用容器
......@@ -32,7 +16,7 @@ let timer: number | null = null;
onMounted(() => {
// 获取当前路径对应的微应用
const microApp = getMicroAppByPath(route.path);
if (!microApp) {
error.value = '未找到对应的微应用配置';
loading.value = false;
......@@ -42,7 +26,7 @@ onMounted(() => {
// 模拟加载延迟和错误处理
timer = window.setTimeout(() => {
loading.value = false;
// 这里可以添加更多的加载逻辑
console.log('[MicroAppContainer] 微应用容器已准备就绪:', microApp.name);
}, 1000);
......@@ -64,14 +48,41 @@ onUnmounted(() => {
const handleRetry = () => {
error.value = '';
loading.value = true;
timer = window.setTimeout(() => {
loading.value = false;
}, 1000);
};
</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>
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.micro-app-container {
width: 100%;
}
......@@ -92,19 +103,10 @@ const handleRetry = () => {
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loading-text {
margin-top: 16px;
color: #666;
font-size: 14px;
color: #666;
}
/* 错误状态 */
......@@ -117,24 +119,24 @@ const handleRetry = () => {
}
.error-icon {
font-size: 48px;
margin-bottom: 16px;
font-size: 48px;
}
.error-text {
color: #ff4d4f;
font-size: 14px;
margin-bottom: 16px;
font-size: 14px;
color: #ff4d4f;
}
.retry-button {
padding: 8px 24px;
background-color: #1890ff;
font-size: 14px;
color: white;
cursor: pointer;
background-color: #1890ff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
......@@ -146,4 +148,3 @@ const handleRetry = () => {
background-color: #096dd9;
}
</style>
import { registerMicroApps, start, addGlobalUncaughtErrorHandler } from 'qiankun';
import {
addGlobalUncaughtErrorHandler,
registerMicroApps,
start,
} from 'qiankun';
import { microApps } from './apps';
import { microAppLifecycles } from './lifecycles';
import { communicationManager } from './communication';
import { microAppLifecycles } from './lifecycles';
/**
* qiankun 配置选项
......@@ -10,7 +15,7 @@ const qiankunConfig = {
// 预加载策略:改为 false,避免在容器未就绪时预加载导致的问题
// 刷新页面时,先让当前路由的微应用正常加载,再进行预加载
prefetch: false,
// 沙箱配置
sandbox: {
// 是否开启严格样式隔离(Shadow DOM)
......@@ -18,13 +23,13 @@ const qiankunConfig = {
// 是否开启实验性样式隔离(scoped css)
experimentalStyleIsolation: true,
},
// 单例模式:同一时间只能有一个微应用在运行
singular: true,
// 获取公共资源的方式
// fetch: customFetch,
// 在第一个微应用加载后再开启预加载
// 这样可以避免刷新时的竞态条件
};
......@@ -37,13 +42,12 @@ export function setupQiankun() {
communicationManager.init();
// 2. 注册微应用
console.log("注册qiankun传参:microApps",microApps);
console.log("注册qiankun钩子:",microAppLifecycles);
console.log('注册qiankun传参:microApps', microApps);
console.log('注册qiankun钩子:', microAppLifecycles);
registerMicroApps(microApps, microAppLifecycles);
// 3. 添加全局错误处理
addGlobalUncaughtErrorHandler((event) => {
// 可以在这里做一些全局错误处理
// 例如:错误上报、错误提示等
const { message } = event as any;
......@@ -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 { communicationManager, broadcast } from './communication';
export * from './types';
export * from './utils';
export type { GlobalState, Notification } from './communication';
......@@ -9,11 +9,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/
beforeLoad: async (app) => {
console.log('[qiankun] before load', app.name);
// 可以在这里做一些加载前的准备工作
// 例如:显示加载动画、设置全局状态等
return Promise.resolve();
},
/**
......@@ -21,12 +19,12 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/
beforeMount: async (app) => {
console.log('[qiankun] before mount', app.name);
// 确保主应用的数据已准备好并同步到全局状态
try {
const { communicationManager } = await import('./communication');
const globalState = communicationManager.getGlobalState();
// 如果用户信息为空,尝试从 Store 获取并同步
if (!globalState.user) {
const { useUserStore } = await import('@/stores');
......@@ -38,8 +36,6 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
} catch (error) {
console.warn('[qiankun] 同步用户信息失败:', error);
}
return Promise.resolve();
},
/**
......@@ -47,11 +43,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/
afterMount: async (app) => {
console.log('[qiankun] after mount', app.name);
// 可以在这里做一些挂载后的处理
// 例如:隐藏加载动画、记录日志、埋点统计等
return Promise.resolve();
},
/**
......@@ -59,11 +53,9 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/
beforeUnmount: async (app) => {
console.log('[qiankun] before unmount', app.name);
// 可以在这里做一些卸载前的清理工作
// 例如:保存状态、显示卸载动画等
return Promise.resolve();
},
/**
......@@ -71,11 +63,8 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
*/
afterUnmount: async (app) => {
console.log('[qiankun] after unmount', app.name);
// 可以在这里做一些卸载后的清理工作
// 例如:清除缓存、重置状态、移除事件监听等
return Promise.resolve();
},
};
import type { FrameworkLifeCycles } from 'qiankun';
/**
* 微应用配置类型
*/
......@@ -7,7 +5,7 @@ export interface MicroAppConfig {
name: string;
entry: string;
container: string;
activeRule: string | string[] | ((location: Location) => boolean);
activeRule: ((location: Location) => boolean) | string | string[];
props?: Record<string, any>;
loader?: (loading: boolean) => void;
}
......@@ -21,17 +19,17 @@ export type MicroAppEnv = 'development' | 'production' | 'test';
* 微应用状态
*/
export enum MicroAppStatus {
NOT_LOADED = 'NOT_LOADED',
LOADING = 'LOADING',
LOADED = 'LOADED',
MOUNTING = 'MOUNTING',
LOADING = 'LOADING',
MOUNTED = 'MOUNTED',
UNMOUNTING = 'UNMOUNTING',
MOUNTING = 'MOUNTING',
NOT_LOADED = 'NOT_LOADED',
UNMOUNTED = 'UNMOUNTED',
UNMOUNTING = 'UNMOUNTING',
}
/**
* qiankun 生命周期钩子类型
*/
export type { FrameworkLifeCycles };
export { type FrameworkLifeCycles } from 'qiankun';
......@@ -73,8 +73,8 @@ export function formatMicroAppPath(path: string, base: string = ''): string {
* @param currentPath 当前路径
*/
export function isMicroAppActive(
activeRule: string | ((location: Location) => boolean),
currentPath: string = window.location.pathname
activeRule: ((location: Location) => boolean) | string,
currentPath: string = window.location.pathname,
): boolean {
if (typeof activeRule === 'function') {
return activeRule(window.location);
......@@ -115,9 +115,9 @@ export function prefetchMicroApp(entry: string): Promise<void> {
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = entry;
link.onload = () => resolve();
link.addEventListener('load', () => resolve());
link.onerror = () => reject(new Error(`预加载失败: ${entry}`));
document.head.appendChild(link);
document.head.append(link);
});
}
......@@ -135,4 +135,3 @@ export function getMicroAppPerformance() {
}
return null;
}
import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores';
import { getToken } from '@/utils/auth';
......@@ -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) => {
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - SCRM 微前端`;
} else {
document.title = 'SCRM 微前端平台';
}
document.title = to.meta.title
? `${to.meta.title} - SCRM 微前端`
: 'SCRM 微前端平台';
// 获取 token
const token = getToken();
......@@ -137,27 +137,7 @@ router.beforeEach(async (to, _from, next) => {
next({ path: '/home' });
} else {
// 检查是否已获取用户信息
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 (userStore.userInfo) {
// 检查权限
if (to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore);
......@@ -179,22 +159,42 @@ router.beforeEach(async (to, _from, 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 {
// 未登录
if (whiteList.includes(to.path)) {
if (whiteList.has(to.path)) {
// 在白名单中,直接放行
next();
} else if (!requiresAuth) {
// 不需要认证的页面,直接放行
next();
} else {
} else if (requiresAuth) {
// 需要认证但未登录,跳转到登录页
next({
path: '/login',
query: { redirect: to.fullPath },
});
} else {
// 不需要认证的页面,直接放行
next();
}
}
});
......@@ -214,19 +214,19 @@ router.afterEach((to, from) => {
async function syncDataToQiankun(userStore: any): Promise<void> {
try {
console.log('[路由守卫] 准备进入微应用,同步数据到 qiankun 全局状态');
// 同步用户信息
if (userStore.userInfo) {
userStore.syncUserToQiankun();
}
// 延迟导入 qiankun 通信模块
const { communicationManager } = await import('@/qiankun/communication');
// 获取当前全局状态,确认数据已同步
const globalState = communicationManager.getGlobalState();
console.log('[路由守卫] 当前全局状态:', globalState);
// 如果用户信息还未同步,强制同步一次
if (!globalState.user && userStore.userInfo) {
console.log('[路由守卫] 检测到用户信息未同步,强制同步');
......@@ -267,4 +267,3 @@ function checkPermission(route: any, userStore: any): boolean {
}
export default router;
import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
/**
* 应用全局状态管理
......@@ -7,16 +8,16 @@ import { ref, computed } from 'vue';
export const useAppStore = defineStore('app', () => {
// 侧边栏状态
const sidebarCollapsed = ref(false);
// 主题模式
const theme = ref<'light' | 'dark'>('light');
const theme = ref<'dark' | 'light'>('light');
// 加载状态
const loading = ref(false);
// 设备类型
const device = ref<'desktop' | 'mobile'>('desktop');
// 语言
const language = ref('zh-CN');
......@@ -44,15 +45,15 @@ export const useAppStore = defineStore('app', () => {
const toggleTheme = () => {
theme.value = theme.value === 'light' ? 'dark' : 'light';
// 应用主题到 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;
document.documentElement.setAttribute('data-theme', newTheme);
document.documentElement.dataset.theme = newTheme;
};
/**
......@@ -81,7 +82,7 @@ export const useAppStore = defineStore('app', () => {
*/
const initApp = () => {
// 从 localStorage 读取保存的主题
const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null;
const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null;
if (savedTheme) {
setTheme(savedTheme);
}
......@@ -97,7 +98,7 @@ export const useAppStore = defineStore('app', () => {
const width = window.innerWidth;
setDevice(width < 768 ? 'mobile' : 'desktop');
};
checkDevice();
window.addEventListener('resize', checkDevice);
};
......@@ -132,4 +133,3 @@ export const useAppStore = defineStore('app', () => {
saveAppState,
};
});
......@@ -2,7 +2,6 @@
* Pinia Stores 统一导出
*/
export { useUserStore } from './user';
export { usePermissionStore } from './permission';
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 { ref } from 'vue';
import { defineStore } from 'pinia';
/**
* 权限路由管理
*/
export const usePermissionStore = defineStore('permission', () => {
// 所有路由
const routes = ref<RouteRecordRaw[]>([]);
// 动态添加的路由
const dynamicRoutes = ref<RouteRecordRaw[]>([]);
// 是否已生成路由
const isRoutesGenerated = ref(false);
......@@ -29,13 +31,13 @@ export const usePermissionStore = defineStore('permission', () => {
const generateRoutes = (roles: string[], permissions: string[]) => {
// 这里可以根据角色和权限动态生成路由
// 目前先返回所有路由,后续可以根据需求扩展
// 示例:根据角色过滤路由
const accessedRoutes = filterRoutes(routes.value, roles, permissions);
dynamicRoutes.value = accessedRoutes;
isRoutesGenerated.value = true;
return accessedRoutes;
};
......@@ -45,13 +47,13 @@ export const usePermissionStore = defineStore('permission', () => {
const filterRoutes = (
routes: RouteRecordRaw[],
roles: string[],
permissions: string[]
permissions: string[],
): RouteRecordRaw[] => {
const res: RouteRecordRaw[] = [];
routes.forEach(route => {
routes.forEach((route) => {
const tmp = { ...route };
// 检查路由权限
if (hasPermission(tmp, roles, permissions)) {
// 递归过滤子路由
......@@ -71,7 +73,7 @@ export const usePermissionStore = defineStore('permission', () => {
const hasPermission = (
route: RouteRecordRaw,
roles: string[],
permissions: string[]
permissions: string[],
): boolean => {
// 如果路由没有设置权限要求,默认可访问
if (!route.meta?.roles && !route.meta?.permissions) {
......@@ -81,7 +83,7 @@ export const usePermissionStore = defineStore('permission', () => {
// 检查角色
if (route.meta?.roles) {
const routeRoles = route.meta.roles as string[];
if (roles.some(role => routeRoles.includes(role))) {
if (roles.some((role) => routeRoles.includes(role))) {
return true;
}
}
......@@ -89,7 +91,9 @@ export const usePermissionStore = defineStore('permission', () => {
// 检查权限
if (route.meta?.permissions) {
const routePermissions = route.meta.permissions as string[];
if (permissions.some(permission => routePermissions.includes(permission))) {
if (
permissions.some((permission) => routePermissions.includes(permission))
) {
return true;
}
}
......@@ -116,4 +120,3 @@ export const usePermissionStore = defineStore('permission', () => {
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 { 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', () => {
// 状态
const token = ref<string>('');
const userInfo = ref<UserInfo | null>(null);
const userInfo = ref<null | UserInfo>(null);
const permissions = ref<string[]>([]);
const roles = ref<string[]>([]);
......@@ -65,7 +71,7 @@ export const useUserStore = defineStore('user', () => {
permissions.value = [];
roles.value = [];
removeToken();
// 同步清空 qiankun 全局状态中的用户信息
syncUserToQiankun();
}
......@@ -98,25 +104,30 @@ export const useUserStore = defineStore('user', () => {
*/
const syncUserToQiankun = () => {
// 延迟导入避免循环依赖
import('@/qiankun/communication').then(({ communicationManager }) => {
if (userInfo.value) {
console.log('syncUserToQiankun.value', userInfo.value);
communicationManager.updateUser({
id: userInfo.value.id,
name: userInfo.value.name,
avatar: userInfo.value.avatar || '👨‍💼',
role: roles.value[0] || 'user',
permissions: permissions.value,
});
console.log('[用户Store] 用户信息已同步到 qiankun 全局状态');
} else {
// 用户退出时,清空全局状态中的用户信息
communicationManager.updateUser(null);
console.log('[用户Store] 用户信息已清空');
}
}).catch(err => {
console.warn('[用户Store] qiankun 通信管理器未初始化或加载失败:', err);
});
import('@/qiankun/communication')
.then(({ communicationManager }) => {
if (userInfo.value) {
console.log('syncUserToQiankun.value', userInfo.value);
communicationManager.updateUser({
id: userInfo.value.id,
name: userInfo.value.name,
avatar: userInfo.value.avatar || '👨‍💼',
role: roles.value[0] || 'user',
permissions: permissions.value,
});
console.log('[用户Store] 用户信息已同步到 qiankun 全局状态');
} else {
// 用户退出时,清空全局状态中的用户信息
communicationManager.updateUser(null);
console.log('[用户Store] 用户信息已清空');
}
})
.catch((error) => {
console.warn(
'[用户Store] qiankun 通信管理器未初始化或加载失败:',
error,
);
});
};
/**
......@@ -132,7 +143,7 @@ export const useUserStore = defineStore('user', () => {
*/
const hasPermission = (permission: string | string[]): boolean => {
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);
};
......@@ -142,7 +153,7 @@ export const useUserStore = defineStore('user', () => {
*/
const hasRole = (role: string | string[]): boolean => {
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);
};
......@@ -180,4 +191,3 @@ export const useUserStore = defineStore('user', () => {
syncUserToQiankun, // 导出同步方法,供外部使用
};
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
......@@ -9,9 +9,10 @@ body,
#app {
width: 100%;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji';
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
font-size: 14px;
line-height: 1.5;
color: #333;
......@@ -19,12 +20,11 @@ body,
}
a {
text-decoration: none;
color: inherit;
text-decoration: none;
}
ul,
ol {
list-style: none;
}
......@@ -41,4 +41,3 @@ export interface ApiError {
message: string;
details?: any;
}
......@@ -5,44 +5,44 @@
export interface MenuItem {
/** 菜单唯一标识 */
id: string;
/** 菜单标题 */
title: string;
/** 路由路径 */
path: string;
/** 菜单图标(可以是 emoji、图标类名或组件) */
icon?: string;
/** 子菜单列表 */
children?: MenuItem[];
/** 是否隐藏菜单项 */
hidden?: boolean;
/** 菜单层级(1-一级,2-二级,3-三级) */
level?: number;
/** 父级菜单ID */
parentId?: string;
/** 扩展元数据 */
meta?: {
/** 是否需要权限 */
requireAuth?: boolean;
/** 权限标识 */
permission?: string;
/** 排序权重 */
order?: number;
/** 徽章数字 */
badge?: number | string;
/** 外部链接 */
externalLink?: string;
/** 是否在面包屑中显示 */
showInBreadcrumb?: boolean;
/** 是否缓存页面 */
keepAlive?: boolean;
/** 徽章数字 */
badge?: number | string;
/** 排序权重 */
order?: number;
/** 权限标识 */
permission?: string;
/** 是否需要权限 */
requireAuth?: boolean;
/** 是否在面包屑中显示 */
showInBreadcrumb?: boolean;
};
}
......@@ -53,16 +53,16 @@ export interface MenuItem {
export interface TopMenuItem {
/** 菜单唯一标识 */
id: string;
/** 菜单标题 */
title: string;
/** 路由路径 */
path: string;
/** 菜单图标 */
icon?: string;
/** 对应的侧边栏菜单 */
sidebarMenus?: MenuItem[];
}
......@@ -73,8 +73,7 @@ export interface TopMenuItem {
export interface BreadcrumbItem {
/** 标题 */
title: string;
/** 路径 */
path?: string;
}
......@@ -67,4 +67,3 @@ export interface UpdateUserInfoParams {
email?: string;
phone?: string;
}
......@@ -9,7 +9,7 @@ const USER_INFO_KEY = 'scrm_user_info';
/**
* 获取 Token
*/
export const getToken = (): string | null => {
export const getToken = (): null | string => {
return localStorage.getItem(TOKEN_KEY);
};
......@@ -30,7 +30,7 @@ export const removeToken = (): void => {
/**
* 获取刷新令牌
*/
export const getRefreshToken = (): string | null => {
export const getRefreshToken = (): null | string => {
return localStorage.getItem(REFRESH_TOKEN_KEY);
};
......@@ -78,4 +78,3 @@ export const clearAuth = (): void => {
removeRefreshToken();
removeUserInfoFromStorage();
};
......@@ -3,6 +3,5 @@
*/
export * from './auth';
export { del, get, patch, post, put, default as request } from './request';
export * from './storage';
export { default as request, get, post, put, del, patch } from './request';
......@@ -2,13 +2,19 @@
* Axios 请求封装
*/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { getToken, clearAuth } from './auth';
import axios, {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
} from 'axios';
import { clearAuth, getToken } from './auth';
// 创建 axios 实例
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 30000,
timeout: 30_000,
headers: {
'Content-Type': 'application/json',
},
......@@ -20,7 +26,7 @@ service.interceptors.request.use(
// 添加 token
const token = getToken();
if (token && config.headers) {
config.headers['Authorization'] = `Bearer ${token}`;
config.headers.Authorization = `Bearer ${token}`;
}
// 添加时间戳防止缓存
......@@ -36,7 +42,7 @@ service.interceptors.request.use(
(error: AxiosError) => {
console.error('请求错误:', error);
return Promise.reject(error);
}
},
);
// 响应拦截器
......@@ -71,20 +77,25 @@ service.interceptors.response.use(
const { status, data } = error.response;
switch (status) {
case 401:
case 401: {
handleUnauthorized();
break;
case 403:
}
case 403: {
console.error('无权限访问');
break;
case 404:
}
case 404: {
console.error('请求的资源不存在');
break;
case 500:
}
case 500: {
console.error('服务器内部错误');
break;
default:
}
default: {
console.error('请求失败:', data);
}
}
} else if (error.request) {
console.error('网络错误,请检查网络连接');
......@@ -93,7 +104,7 @@ service.interceptors.response.use(
}
return Promise.reject(error);
}
},
);
/**
......@@ -102,7 +113,7 @@ service.interceptors.response.use(
const handleUnauthorized = () => {
console.warn('登录已过期,请重新登录');
clearAuth();
// 跳转到登录页
if (window.location.pathname !== '/login') {
window.location.href = '/login';
......@@ -119,37 +130,56 @@ export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
/**
* 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 });
};
/**
* 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);
};
/**
* 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);
};
/**
* 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 });
};
/**
* 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);
};
export default service;
......@@ -6,6 +6,13 @@
type StorageType = 'local' | 'session';
class Storage {
/**
* 获取存储项数量
*/
get length(): number {
return this.storage.length;
}
private storage: globalThis.Storage;
constructor(type: StorageType = 'local') {
......@@ -13,20 +20,20 @@ class Storage {
}
/**
* 设置存储项
* 清空所有存储项
*/
set(key: string, value: any): void {
clear(): void {
try {
const serializedValue = JSON.stringify(value);
this.storage.setItem(key, serializedValue);
this.storage.clear();
} catch (error) {
console.error('清空存储失败:', error);
}
}
/**
* 获取存储项
*/
get<T = any>(key: string): T | null {
get<T = any>(key: string): null | T {
try {
const item = this.storage.getItem(key);
return item ? JSON.parse(item) : null;
......@@ -37,25 +44,24 @@ class Storage {
}
/**
* 移除存储项
* 获取带过期时间的存储项
*/
remove(key: string): void {
try {
this.storage.removeItem(key);
} catch (error) {
console.error('移除数据失败:', error);
getWithExpiry<T = any>(key: string): null | T {
const item = this.get<{ expiry: number; value: T }>(key);
if (!item) {
return null;
}
}
/**
* 清空所有存储项
*/
clear(): void {
try {
this.storage.clear();
} catch (error) {
console.error('清空存储失败:', error);
const now = Date.now();
// 检查是否过期
if (now > item.expiry) {
this.remove(key);
return null;
}
return item.value;
}
/**
......@@ -73,44 +79,37 @@ class Storage {
}
/**
* 获取存储项数量
* 移除存储项
*/
get length(): number {
return this.storage.length;
remove(key: string): void {
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 {
const now = new Date().getTime();
const now = Date.now();
const item = {
value,
expiry: now + expiryInMs,
};
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');
export const sessionCache = new Storage('session');
export default Storage;
<template>
<!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 -->
<div id="subapp-container" class="micro-app-container"></div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
......@@ -18,14 +13,19 @@ onUnmounted(() => {
});
</script>
<template>
<!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 -->
<div id="subapp-container" class="micro-app-container"></div>
</template>
<style scoped>
.micro-app-container {
width: 100%;
height: 100%;
min-height: 500px;
/* 移除内边距,让微应用完全填充容器 */
padding: 0;
margin: 0;
}
</style>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/home');
};
</script>
<template>
<div class="not-found-page">
<div class="not-found-content">
......@@ -9,16 +19,6 @@
</div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/home');
};
</script>
<style scoped>
.not-found-page {
display: flex;
......@@ -29,27 +29,27 @@ const goHome = () => {
}
.not-found-content {
text-align: center;
color: #fff;
text-align: center;
}
.error-code {
margin-bottom: 24px;
font-size: 120px;
font-weight: 700;
line-height: 1;
margin-bottom: 24px;
text-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
text-shadow: 0 4px 8px rgb(0 0 0 / 20%);
}
.error-title {
margin-bottom: 16px;
font-size: 32px;
font-weight: 600;
margin-bottom: 16px;
}
.error-desc {
font-size: 16px;
margin-bottom: 32px;
font-size: 16px;
opacity: 0.9;
}
......@@ -58,17 +58,16 @@ const goHome = () => {
font-size: 16px;
font-weight: 500;
color: #667eea;
cursor: pointer;
background: #fff;
border: none;
border-radius: 24px;
cursor: pointer;
box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
transition: all 0.3s;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.back-button:hover {
box-shadow: 0 6px 16px rgb(0 0 0 / 20%);
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}
</style>
{
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
/* Path alias */
"baseUrl": ".",
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"allowImportingTsExtensions": true,
/* Linting */
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Path alias */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"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": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
}
import { defineConfig } from 'vite';
import { resolve } from 'node:path';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
......@@ -36,4 +37,3 @@ export default defineConfig({
cssCodeSplit: false,
},
});
/// <reference types="vite/client" />
// / <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
......@@ -15,4 +16,3 @@ declare global {
}
export {};
{
"name": "@venus/venus-micro-app",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
......@@ -11,22 +11,22 @@
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "catalog:",
"vue-router": "catalog:",
"pinia": "catalog:",
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"axios": "catalog:"
"axios": "catalog:",
"pinia": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vue-tsc": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "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 { createApp } from 'vue';
import { createPinia } from 'pinia';
import { createRouter } from './router';
import {
renderWithQiankun,
qiankunWindow,
type QiankunProps,
renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue';
import { createRouter } from './router';
import './style.css';
let app: VueApp<Element> | null = null;
let app: null | VueApp<Element> = null;
let router: any = null;
/**
......@@ -19,34 +24,34 @@ let router: any = null;
*/
async function render(props: QiankunProps = {}) {
const { container } = props;
app = createApp(App);
// 配置 Pinia
app.use(createPinia());
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? (props.routerBase || '/subapp-vue')
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? props.routerBase || '/subapp-vue'
: '/';
router = createRouter(routerBase);
app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication;
}
// 挂载应用
const containerEl = container
? container.querySelector('#app')
: document.getElementById('app');
: document.querySelector('#app');
if (containerEl) {
app.mount(containerEl as Element);
} else {
......@@ -86,13 +91,13 @@ export async function mount(props: QiankunProps) {
*/
export async function unmount(props: QiankunProps) {
console.log('[Vue3 微应用] unmount', props);
// 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.destroy();
}
if (app) {
app.unmount();
app = null;
......@@ -117,4 +122,3 @@ renderWithQiankun({
unmount,
update,
});
import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw, Router } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
......@@ -74,4 +75,3 @@ export function createRouter(base: string = '/'): Router {
return router;
}
......@@ -5,31 +5,29 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
line-height: 1.5;
color-scheme: light dark;
font-synthesis: none;
text-rendering: optimizeLegibility;
text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
margin: 0;
}
#app {
......@@ -44,22 +42,22 @@ body {
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
background: rgb(255 255 255 / 10%);
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
background: rgb(255 255 255 / 30%);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
background: rgb(255 255 255 / 50%);
}
/* 选中文本样式 */
::selection {
background: rgba(255, 255, 255, 0.3);
color: white;
background: rgb(255 255 255 / 30%);
}
/* 响应式 */
......@@ -68,4 +66,3 @@ body {
font-size: 14px;
}
}
......@@ -4,35 +4,35 @@ import { onUnmounted } from 'vue';
* 全局状态接口定义(与基座保持一致)
*/
export interface GlobalState {
user: {
user: null | {
avatar: string;
id: string;
name: string;
avatar: string;
role: string;
permissions: string[];
} | null;
role: string;
};
theme: {
mode: 'light' | 'dark';
mode: 'dark' | 'light';
primaryColor: string;
};
notifications: Notification[];
config: {
apiBaseUrl: string;
timeout: number;
};
// 当前激活的菜单信息
currentMenu?: {
menuId: string;
menuTitle: string;
menuPath: string;
currentMenu?: null | {
menuIcon?: string;
menuId: string;
menuMeta?: Record<string, any>;
menuPath: string;
menuTitle: string;
timestamp: number;
} | null;
};
}
/**
......@@ -40,7 +40,7 @@ export interface GlobalState {
*/
export interface Notification {
id: string;
type: 'success' | 'warning' | 'error' | 'info';
type: 'error' | 'info' | 'success' | 'warning';
title: string;
message: string;
timestamp: number;
......@@ -55,7 +55,7 @@ export interface QiankunProps {
routerBase?: string;
onGlobalStateChange?: (
callback: (state: GlobalState, prev: GlobalState) => void,
fireImmediately?: boolean
fireImmediately?: boolean,
) => void;
setGlobalState?: (state: Partial<GlobalState>) => void;
[key: string]: any;
......@@ -65,10 +65,31 @@ export interface QiankunProps {
* 子应用通信管理器
*/
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 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 {
const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => {
console.log('[子应用通信] 全局状态变化:', state, prev);
// 缓存当前状态
this.currentState = state;
// 触发所有监听器
this.listeners.forEach(listener => {
this.listeners.forEach((listener) => {
listener(state, prev);
});
},
true // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
);
// 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') {
......@@ -100,7 +121,7 @@ class SubAppCommunicationManager {
}
console.log('[子应用通信] 通信管理器初始化完成');
// 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递
setTimeout(() => {
if (this.props?.onGlobalStateChange) {
......@@ -110,48 +131,30 @@ class SubAppCommunicationManager {
}
/**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/**
* 监听全局状态变化
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(callback: (state: GlobalState, prev: GlobalState) => void): () => void {
onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) {
console.log('[子应用通信] 立即触发回调,使用缓存的全局状态');
callback(this.currentState, {} as GlobalState);
}
return () => {
const index = this.listeners.indexOf(callback);
if (index > -1) {
if (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 通知消息
*/
......@@ -179,16 +182,16 @@ class SubAppCommunicationManager {
}
/**
* 销毁
* 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) {
this.props.setGlobalState(state);
console.log('[子应用通信] 全局状态已更新:', state);
} else {
console.warn('[子应用通信] setGlobalState 方法不可用');
}
this.listeners = [];
this.props = null;
console.log('[子应用通信] 通信管理器已销毁');
}
}
......@@ -200,15 +203,15 @@ export const subAppCommunication = new SubAppCommunicationManager();
* @param callback 状态变化回调
*/
export function useGlobalState(
callback: (state: GlobalState, prev: GlobalState) => void
callback: (state: GlobalState, prev: GlobalState) => void,
) {
const unsubscribe = subAppCommunication.onStateChange(callback);
// 在组件卸载时自动取消订阅
onUnmounted(() => {
unsubscribe();
});
return unsubscribe;
}
......@@ -218,7 +221,7 @@ export function useGlobalState(
export function notify(
type: Notification['type'],
title: string,
message: string
message: string,
) {
subAppCommunication.sendNotification({
type,
......@@ -226,4 +229,3 @@ export function notify(
message,
});
}
<script setup lang="ts">
// About 页面
</script>
<template>
<div class="about-view">
<div class="content-card">
<h1>📖 关于本应用</h1>
<section class="section">
<h2>技术栈</h2>
<ul class="tech-list">
......@@ -44,10 +48,6 @@ pnpm build</code></pre>
</div>
</template>
<script setup lang="ts">
// About 页面
</script>
<style scoped>
.about-view {
max-width: 900px;
......@@ -55,15 +55,15 @@ pnpm build</code></pre>
}
.content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 2rem 0;
margin: 0 0 2rem;
font-size: 2rem;
}
......@@ -72,31 +72,31 @@ pnpm build</code></pre>
}
.section h2 {
margin: 0 0 1rem 0;
margin: 0 0 1rem;
font-size: 1.5rem;
color: rgba(255, 255, 255, 0.95);
color: rgb(255 255 255 / 95%);
}
.tech-list,
.feature-list {
list-style: none;
padding: 0;
margin: 0;
list-style: none;
}
.tech-list li,
.feature-list li {
padding: 0.5rem 0;
opacity: 0.9;
line-height: 1.6;
opacity: 0.9;
}
.code-block {
background: rgba(0, 0, 0, 0.3);
padding: 1.5rem;
border-radius: 0.5rem;
border: 1px solid rgba(255, 255, 255, 0.1);
overflow-x: auto;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.5rem;
}
.code-block pre {
......@@ -110,4 +110,3 @@ pnpm build</code></pre>
color: #a8e6cf;
}
</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>
<div class="home-view">
<div class="hero-section">
......@@ -77,7 +123,9 @@
</div>
<div class="info-item">
<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>
......@@ -112,10 +160,23 @@
</div>
<!-- 通知消息 -->
<div v-if="globalState?.notifications && globalState.notifications.length > 0" 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', notification.type]">{{ notification.type }}</span>
<div
v-if="
globalState?.notifications && globalState.notifications.length > 0
"
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-from" v-if="notification.from">来自: {{ notification.from }}</span>
</div>
......@@ -137,49 +198,6 @@
</div>
</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>
.home-view {
max-width: 1200px;
......@@ -187,14 +205,14 @@ const sendTestNotification = () => {
}
.hero-section {
text-align: center;
padding: 3rem 0;
margin-bottom: 3rem;
text-align: center;
}
.hero-title {
font-size: 2.5rem;
margin-bottom: 1rem;
font-size: 2.5rem;
font-weight: 700;
}
......@@ -211,27 +229,27 @@ const sendTestNotification = () => {
}
.card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
transition: all 0.3s ease;
}
.card:hover {
background: rgb(255 255 255 / 15%);
box-shadow: 0 10px 30px rgb(0 0 0 / 20%);
transform: translateY(-5px);
background: rgba(255, 255, 255, 0.15);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}
.card-icon {
font-size: 3rem;
margin-bottom: 1rem;
font-size: 3rem;
}
.card h3 {
margin: 0 0 0.5rem 0;
margin: 0 0 0.5rem;
font-size: 1.3rem;
}
......@@ -241,15 +259,15 @@ const sendTestNotification = () => {
}
.info-section {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
}
.info-section h2 {
margin: 0 0 1.5rem 0;
margin: 0 0 1.5rem;
font-size: 1.5rem;
}
......@@ -261,56 +279,56 @@ const sendTestNotification = () => {
.info-item {
display: flex;
align-items: center;
gap: 1rem;
align-items: center;
}
.info-label {
font-weight: 600;
min-width: 100px;
font-weight: 600;
}
.info-value {
padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 0.5rem;
font-family: monospace;
background: rgb(255 255 255 / 10%);
border-radius: 0.5rem;
}
.btn-primary,
.btn-secondary {
padding: 0.5rem 1rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-primary {
background: rgba(76, 175, 80, 0.8);
color: white;
background: rgb(76 175 80 / 80%);
}
.btn-primary:hover {
background: rgba(76, 175, 80, 1);
background: rgb(76 175 80 / 100%);
}
.btn-secondary {
background: rgba(244, 67, 54, 0.8);
color: white;
background: rgb(244 67 54 / 80%);
}
.btn-secondary:hover {
background: rgba(244, 67, 54, 1);
background: rgb(244 67 54 / 100%);
}
.data-group {
margin-bottom: 1.5rem;
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-left: 3px solid rgba(255, 255, 255, 0.3);
}
.data-group:last-child {
......@@ -318,7 +336,7 @@ const sendTestNotification = () => {
}
.data-group-title {
margin: 0 0 1rem 0;
margin: 0 0 1rem;
font-size: 1.1rem;
font-weight: 600;
opacity: 0.9;
......@@ -326,12 +344,12 @@ const sendTestNotification = () => {
.notification-item {
display: flex;
align-items: center;
gap: 0.75rem;
align-items: center;
padding: 0.75rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 0.375rem;
margin-bottom: 0.5rem;
background: rgb(255 255 255 / 5%);
border-radius: 0.375rem;
}
.notification-item:last-child {
......@@ -340,30 +358,30 @@ const sendTestNotification = () => {
.notification-type {
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
border-radius: 0.25rem;
}
.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 {
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 {
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 {
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 {
......@@ -377,8 +395,8 @@ const sendTestNotification = () => {
}
.no-data {
text-align: center;
padding: 2rem;
text-align: center;
opacity: 0.7;
}
......@@ -388,28 +406,27 @@ const sendTestNotification = () => {
}
.actions {
margin-top: 1.5rem;
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1.5rem;
}
.btn-action {
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(33 150 243 / 80%);
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
background: rgba(33, 150, 243, 0.8);
color: white;
font-size: 1rem;
}
.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);
box-shadow: 0 5px 15px rgba(33, 150, 243, 0.3);
}
</style>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/');
};
</script>
<template>
<div class="notfound-view">
<div class="content-card">
......@@ -9,70 +19,58 @@
</div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/');
};
</script>
<style scoped>
.notfound-view {
max-width: 600px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
max-width: 600px;
min-height: 400px;
margin: 0 auto;
}
.content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 3rem;
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
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 {
margin-bottom: 1rem;
font-size: 6rem;
font-weight: 700;
margin-bottom: 1rem;
background: linear-gradient(45deg, #fff, rgba(255, 255, 255, 0.6));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%));
background-clip: text;
-webkit-text-fill-color: transparent;
}
.content-card h1 {
margin: 0 0 1rem 0;
margin: 0 0 1rem;
font-size: 2rem;
}
.content-card p {
margin: 0 0 2rem 0;
margin: 0 0 2rem;
opacity: 0.9;
}
.btn-home {
padding: 0.75rem 2rem;
background: rgba(76, 175, 80, 0.8);
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
font-size: 1rem;
transition: all 0.3s ease;
}
.btn-home:hover {
background: rgba(76, 175, 80, 1);
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
</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>
<div class="settings-view">
<div class="content-card">
......@@ -109,56 +159,6 @@
</div>
</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>
.settings-view {
max-width: 1200px;
......@@ -166,15 +166,15 @@ const resetSettings = () => {
}
.content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 2rem 0;
margin: 0 0 2rem;
font-size: 2rem;
}
......@@ -186,22 +186,22 @@ const resetSettings = () => {
}
.setting-group {
background: rgba(255, 255, 255, 0.05);
padding: 1.5rem;
background: rgb(255 255 255 / 5%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.setting-group h2 {
margin: 0 0 1rem 0;
margin: 0 0 1rem;
font-size: 1.2rem;
color: rgba(255, 255, 255, 0.95);
color: rgb(255 255 255 / 95%);
}
.setting-item {
display: flex;
justify-content: space-between;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
......@@ -212,11 +212,11 @@ const resetSettings = () => {
.select-input,
.number-input {
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;
color: white;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 0.5rem;
}
.number-input {
......@@ -238,52 +238,51 @@ const resetSettings = () => {
.btn-save,
.btn-reset {
padding: 0.75rem 2rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-save {
background: rgba(76, 175, 80, 0.8);
color: white;
background: rgb(76 175 80 / 80%);
}
.btn-save:hover {
background: rgba(76, 175, 80, 1);
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
.btn-reset {
background: rgba(158, 158, 158, 0.8);
color: white;
background: rgb(158 158 158 / 80%);
}
.btn-reset:hover {
background: rgba(158, 158, 158, 1);
background: rgb(158 158 158 / 100%);
transform: translateY(-2px);
}
.current-settings {
background: rgba(0, 0, 0, 0.3);
padding: 1.5rem;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.current-settings h3 {
margin: 0 0 1rem 0;
margin: 0 0 1rem;
font-size: 1.1rem;
}
.current-settings pre {
margin: 0;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.6;
color: #a8e6cf;
overflow-x: auto;
}
</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">
import { ref } from 'vue';
......@@ -53,7 +5,7 @@ interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
role: 'admin' | 'guest' | 'user';
active: boolean;
}
......@@ -105,15 +57,69 @@ const editUser = (user: User) => {
};
const deleteUser = (id: number) => {
const index = users.value.findIndex(u => u.id === id);
if (index > -1) {
if (confirm(`确定要删除用户 ${users.value[index].name} 吗?`)) {
users.value.splice(index, 1);
}
const index = users.value.findIndex((u) => u.id === id);
if (
index !== -1 &&
confirm(`确定要删除用户 ${users.value[index].name} 吗?`)
) {
users.value.splice(index, 1);
}
};
</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>
.user-view {
max-width: 1200px;
......@@ -121,15 +127,15 @@ const deleteUser = (id: number) => {
}
.content-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 1.5rem 0;
margin: 0 0 1.5rem;
font-size: 2rem;
}
......@@ -139,17 +145,17 @@ const deleteUser = (id: number) => {
.btn-add {
padding: 0.75rem 1.5rem;
background: rgba(76, 175, 80, 0.8);
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-add:hover {
background: rgba(76, 175, 80, 1);
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
......@@ -163,19 +169,19 @@ const deleteUser = (id: number) => {
}
.user-table thead {
background: rgba(255, 255, 255, 0.1);
background: rgb(255 255 255 / 10%);
}
.user-table th,
.user-table td {
padding: 1rem;
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 {
font-weight: 600;
color: rgba(255, 255, 255, 0.95);
color: rgb(255 255 255 / 95%);
}
.user-table tbody tr {
......@@ -183,70 +189,69 @@ const deleteUser = (id: number) => {
}
.user-table tbody tr:hover {
background: rgba(255, 255, 255, 0.05);
background: rgb(255 255 255 / 5%);
}
.badge {
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
}
.badge-admin {
background: rgba(244, 67, 54, 0.8);
background: rgb(244 67 54 / 80%);
}
.badge-user {
background: rgba(33, 150, 243, 0.8);
background: rgb(33 150 243 / 80%);
}
.badge-guest {
background: rgba(158, 158, 158, 0.8);
background: rgb(158 158 158 / 80%);
}
.status {
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
}
.status-active {
background: rgba(76, 175, 80, 0.8);
background: rgb(76 175 80 / 80%);
}
.status-inactive {
background: rgba(158, 158, 158, 0.8);
background: rgb(158 158 158 / 80%);
}
.btn-edit,
.btn-delete {
padding: 0.5rem 1rem;
margin-right: 0.5rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
}
.btn-edit {
background: rgba(33, 150, 243, 0.8);
color: white;
background: rgb(33 150 243 / 80%);
}
.btn-edit:hover {
background: rgba(33, 150, 243, 1);
background: rgb(33 150 243 / 100%);
}
.btn-delete {
background: rgba(244, 67, 54, 0.8);
color: white;
background: rgb(244 67 54 / 80%);
}
.btn-delete:hover {
background: rgba(244, 67, 54, 1);
background: rgb(244 67 54 / 100%);
}
</style>
{
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
/* Path Alias */
"baseUrl": ".",
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"allowImportingTsExtensions": true,
/* Linting */
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Path Alias */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"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": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
}
import { defineConfig } from 'vite';
import { resolve } from 'node:path';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { defineConfig } from 'vite';
import qiankun from 'vite-plugin-qiankun';
const PORT = 8081;
......@@ -12,59 +13,58 @@ const APP_NAME = 'subapp-vue'; // 与基座配置的 name 一致
export default defineConfig(({ mode, command }) => {
const isDev = mode === 'development';
const isServe = command === 'serve';
return {
base: isDev && isServe ? `http://localhost:${PORT}/` : `/${APP_NAME}/`, // 生产环境使用应用名作为基础路径
plugins: [
vue(),
vueJsx(),
// 自动导入 Vue 相关函数
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts',
eslintrc: {
enabled: false,
base: isDev && isServe ? `http://localhost:${PORT}/` : `/${APP_NAME}/`, // 生产环境使用应用名作为基础路径
plugins: [
vue(),
vueJsx(),
// 自动导入 Vue 相关函数
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts',
eslintrc: {
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: {
port: PORT,
cors: true, // 允许跨域
host: true,
origin: `http://localhost:${PORT}`, // 设置资源加载的 origin
headers: {
'Access-Control-Allow-Origin': '*', // 允许所有来源
server: {
port: PORT,
cors: true, // 允许跨域
host: true,
origin: `http://localhost:${PORT}`, // 设置资源加载的 origin
headers: {
'Access-Control-Allow-Origin': '*', // 允许所有来源
},
},
},
build: {
target: 'esnext',
minify: false, // 开发环境不压缩,便于调试
cssCodeSplit: false, // css 不拆分
rollupOptions: {
output: {
// qiankun 需要的输出格式
format: 'umd',
// UMD 库名称,必须与应用名称一致
name: `qiankunApp_${APP_NAME.replace(/-/g, '_')}`,
entryFileNames: 'assets/[name].js',
chunkFileNames: 'assets/[name].[hash].js',
assetFileNames: 'assets/[name].[hash].[ext]',
build: {
target: 'esnext',
minify: false, // 开发环境不压缩,便于调试
cssCodeSplit: false, // css 不拆分
rollupOptions: {
output: {
// qiankun 需要的输出格式
format: 'umd',
// UMD 库名称,必须与应用名称一致
name: `qiankunApp_${APP_NAME.replaceAll('-', '_')}`,
entryFileNames: 'assets/[name].js',
chunkFileNames: 'assets/[name].[hash].js',
assetFileNames: 'assets/[name].[hash].[ext]',
},
},
},
},
};
});
import { defineConfig } from 'vitepress'
import { defineConfig } from 'vitepress';
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "Venus Admin",
description: "现代化的 Vue3 中后台管理系统框架",
title: 'Venus Admin',
description: '现代化的 Vue3 中后台管理系统框架',
lang: 'zh-CN',
// 主题配置
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
logo: '/logo.svg',
nav: [
{ text: '首页', link: '/' },
{ text: '指南', link: '/guide/introduction' },
......@@ -19,10 +19,13 @@ export default defineConfig({
{
text: '相关链接',
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: {
......@@ -33,7 +36,7 @@ export default defineConfig({
{ text: '简介', link: '/guide/introduction' },
{ text: '快速开始', link: '/guide/quick-start' },
{ text: '项目配置', link: '/guide/configuration' },
]
],
},
{
text: '基础',
......@@ -42,7 +45,7 @@ export default defineConfig({
{ text: '路由和菜单', link: '/guide/router-menu' },
{ text: '权限管理', link: '/guide/permission' },
{ text: '状态管理', link: '/guide/state-management' },
]
],
},
{
text: '进阶',
......@@ -51,8 +54,8 @@ export default defineConfig({
{ text: '国际化', link: '/guide/i18n' },
{ text: '构建和部署', link: '/guide/build-deploy' },
{ text: '环境变量', link: '/guide/env-variables' },
]
}
],
},
],
'/components/': [
{
......@@ -63,8 +66,8 @@ export default defineConfig({
{ text: '表格组件', link: '/components/table' },
{ text: '弹窗组件', link: '/components/modal' },
{ text: '图表组件', link: '/components/chart' },
]
}
],
},
],
'/api/': [
{
......@@ -73,13 +76,13 @@ export default defineConfig({
{ text: '核心 API', link: '/api/core' },
{ text: '工具函数', link: '/api/utils' },
{ text: '类型定义', link: '/api/types' },
]
}
]
],
},
],
},
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({
translations: {
button: {
buttonText: '搜索文档',
buttonAriaLabel: '搜索文档'
buttonAriaLabel: '搜索文档',
},
modal: {
noResultsText: '无法找到相关结果',
resetButtonTitle: '清除查询条件',
footer: {
selectText: '选择',
navigateText: '切换'
}
}
}
}
}
}
navigateText: '切换',
},
},
},
},
},
},
},
// 编辑链接
editLink: {
pattern: 'https://github.com/venusjs/vue-venus-admin/edit/main/docs/:path',
text: '在 GitHub 上编辑此页'
pattern:
'https://github.com/venusjs/vue-venus-admin/edit/main/docs/:path',
text: '在 GitHub 上编辑此页',
},
// 页脚
footer: {
message: '基于 MIT 许可发布',
copyright: 'Copyright © 2024-present Venus Admin'
copyright: 'Copyright © 2024-present Venus Admin',
},
// 大纲配置
outline: {
level: [2, 3],
label: '页面导航'
label: '页面导航',
},
// 文档页脚
docFooter: {
prev: '上一页',
next: '下一页'
next: '下一页',
},
// 最后更新时间
......@@ -136,8 +140,8 @@ export default defineConfig({
text: '最后更新于',
formatOptions: {
dateStyle: 'short',
timeStyle: 'short'
}
timeStyle: 'short',
},
},
// 返回顶部
......@@ -145,16 +149,16 @@ export default defineConfig({
sidebarMenuLabel: '菜单',
darkModeSwitchLabel: '主题',
lightModeSwitchTitle: '切换到浅色模式',
darkModeSwitchTitle: '切换到深色模式'
darkModeSwitchTitle: '切换到深色模式',
},
// Markdown 配置
markdown: {
theme: {
light: 'github-light',
dark: 'github-dark'
dark: 'github-dark',
},
lineNumbers: true
lineNumbers: true,
},
// 构建配置
......@@ -167,7 +171,6 @@ export default defineConfig({
['link', { rel: 'icon', href: '/favicon.ico' }],
['meta', { name: 'theme-color', content: '#646cff' }],
['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!