Commit dd6d98b2 by 林磊

Merge branch 'faet_lint_error' into 'dev'

Faet lint error into Dev

See merge request !11
2 parents 2d4b771a 0d85e353
Showing 186 changed files with 1601 additions and 1824 deletions
name: 📚 Documentation name: 📚 Documentation
description: Report an issue with Vben Admin Website to help us make it better. description: Report an issue with Vben Admin Website to help us make it better.
title: 'Docs: ' title: "Docs: "
labels: [documentation] labels: [documentation]
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
Thanks for taking the time to fill out this issue! Thanks for taking the time to fill out this issue!
- type: checkboxes - type: checkboxes
id: documentation_is id: documentation_is
attributes: attributes:
label: Documentation is label: Documentation is
options: options:
- label: Missing - label: Missing
- label: Outdated - label: Outdated
- label: Confusing - label: Confusing
- label: Not sure? - label: Not sure?
- type: textarea - type: textarea
id: description id: description
attributes: attributes:
label: Explain in Detail label: Explain in Detail
description: A clear and concise description of your suggestion. If you intend to submit a PR for this issue, tell us in the description. Thanks! description: A clear and concise description of your suggestion. If you intend to submit a PR for this issue, tell us in the description. Thanks!
placeholder: The description of ... page is not clear. I thought it meant ... but it wasn't. placeholder: The description of ... page is not clear. I thought it meant ... but it wasn't.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: suggestion id: suggestion
attributes: attributes:
label: Your Suggestion for Changes label: Your Suggestion for Changes
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: reproduction-steps id: reproduction-steps
attributes: attributes:
label: Steps to reproduce label: Steps to reproduce
description: Please provide any reproduction steps that may need to be described. E.g. if it happens only when running the dev or build script make sure it's clear which one to use. description: Please provide any reproduction steps that may need to be described. E.g. if it happens only when running the dev or build script make sure it's clear which one to use.
placeholder: Run `pnpm install` followed by `pnpm run docs:dev` placeholder: Run `pnpm install` followed by `pnpm run docs:dev`
name: ✨ New Feature Proposal name: ✨ New Feature Proposal
description: Propose a new feature to be added to Vben Admin description: Propose a new feature to be added to Vben Admin
title: 'FEATURE: ' title: "FEATURE: "
labels: ['enhancement: pending triage'] labels: ["enhancement: pending triage"]
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
Thank you for suggesting a feature for our project! Please fill out the information below to help us understand and implement your request! Thank you for suggesting a feature for our project! Please fill out the information below to help us understand and implement your request!
- type: dropdown - type: dropdown
id: version id: version
attributes: attributes:
label: Version label: Version
description: What version of our software are you running? description: What version of our software are you running?
options: options:
- Vben Admin V5 - Vben Admin V5
- Vben Admin V2 - Vben Admin V2
default: 0 default: 0
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: description id: description
attributes: attributes:
label: Description label: Description
description: A detailed description of the feature request. description: A detailed description of the feature request.
placeholder: Please describe the feature you would like to see, and why it would be useful. placeholder: Please describe the feature you would like to see, and why it would be useful.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: proposed-solution id: proposed-solution
attributes: attributes:
label: Proposed Solution label: Proposed Solution
description: A clear and concise description of what you want to happen. description: A clear and concise description of what you want to happen.
placeholder: Describe the solution you'd like to see placeholder: Describe the solution you'd like to see
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: alternatives id: alternatives
attributes: attributes:
label: Alternatives Considered label: Alternatives Considered
description: | description: |
A clear and concise description of any alternative solutions or features you've considered. A clear and concise description of any alternative solutions or features you've considered.
placeholder: Describe any alternative solutions or features you've considered placeholder: Describe any alternative solutions or features you've considered
validations: validations:
required: false required: false
- type: input - type: input
id: additional-context id: additional-context
attributes: attributes:
label: Additional Context label: Additional Context
description: Add any other context or screenshots about the feature request here. description: Add any other context or screenshots about the feature request here.
placeholder: Any additional information placeholder: Any additional information
validations: validations:
required: false required: false
- type: checkboxes - type: checkboxes
id: checkboxes id: checkboxes
attributes: attributes:
label: Validations label: Validations
description: Before submitting the issue, please make sure you do the following description: Before submitting the issue, please make sure you do the following
options: options:
- label: Read the [docs](https://doc.vben.pro/) - label: Read the [docs](https://doc.vben.pro/)
required: true required: true
- label: Ensure the code is up to date. (Some issues have been fixed in the latest version) - label: Ensure the code is up to date. (Some issues have been fixed in the latest version)
required: true required: true
- label: I have searched the [existing issues](https://github.com/vbenjs/vue-vben-admin/issues) and checked that my issue does not duplicate any existing issues. - label: I have searched the [existing issues](https://github.com/vbenjs/vue-vben-admin/issues) and checked that my issue does not duplicate any existing issues.
required: true required: true
...@@ -19,10 +19,10 @@ ...@@ -19,10 +19,10 @@
- 从相关分支(例如 main)检出一个话题分支,并针对该分支进行合并。 - 从相关分支(例如 main)检出一个话题分支,并针对该分支进行合并。
- 如果添加新功能: - 如果添加新功能:
- 提供一个令人信服的理由来添加此功能。理想情况下,你应该先打开一个建议问题并在处理前获得批准。 - 提供一个令人信服的理由来添加此功能。理想情况下,你应该先打开一个建议问题并在处理前获得批准。
- 如果修复 Bug: - 如果修复 Bug:
- 在 PR 中提供 Bug 的详细描述。最好提供实时演示。 - 在 PR 中提供 Bug 的详细描述。最好提供实时演示。
- 在处理 PR 时可以有多个小提交 - GitHub 可以在合并前自动压缩它们。 - 在处理 PR 时可以有多个小提交 - GitHub 可以在合并前自动压缩它们。
......
version: 2 version: 2
updates: updates:
- package-ecosystem: npm - package-ecosystem: npm
directory: '/' directory: "/"
schedule: schedule:
interval: daily interval: daily
groups: groups:
non-breaking-changes: non-breaking-changes:
update-types: [minor, patch] update-types: [minor, patch]
- package-ecosystem: github-actions - package-ecosystem: github-actions
directory: '/' directory: "/"
schedule: schedule:
interval: weekly interval: weekly
groups: groups:
non-breaking-changes: non-breaking-changes:
update-types: [minor, patch] update-types: [minor, patch]
name-template: 'v$RESOLVED_VERSION' name-template: "v$RESOLVED_VERSION"
tag-template: 'v$RESOLVED_VERSION' tag-template: "v$RESOLVED_VERSION"
version-template: $MAJOR.$MINOR.$PATCH version-template: $MAJOR.$MINOR.$PATCH
change-template: '* $TITLE (#$NUMBER) @$AUTHOR' change-template: "* $TITLE (#$NUMBER) @$AUTHOR"
template: | template: |
# What's Changed # What's Changed
$CHANGES $CHANGES
**Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION **Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION
categories: categories:
- title: '🚀 Features' - title: "🚀 Features"
labels: labels:
- 'feature' - "feature"
- title: '🐞 Bug Fixes' - title: "🐞 Bug Fixes"
labels: labels:
- 'bug' - "bug"
- title: '📈 Performance & Enhancement' - title: "📈 Performance & Enhancement"
labels: labels:
- 'perf' - "perf"
- 'enhancement' - "enhancement"
- title: 📝 Documentation - title: 📝 Documentation
labels: labels:
- 'documentation' - "documentation"
- title: 👻 Maintenance - title: 👻 Maintenance
labels: labels:
- 'chore' - "chore"
- 'dependencies' - "dependencies"
# collapse-after: 12 # collapse-after: 12
- title: 🚦 Tests - title: 🚦 Tests
labels: labels:
- 'tests' - "tests"
- title: 'Breaking' - title: "Breaking"
label: 'breaking' label: "breaking"
version-resolver: version-resolver:
major: major:
labels: labels:
- 'major' - "major"
- 'breaking' - "breaking"
minor: minor:
labels: labels:
- 'minor' - "minor"
patch: patch:
labels: labels:
- 'feature' - "feature"
- 'patch' - "patch"
- 'bug' - "bug"
- 'maintenance' - "maintenance"
- 'docs' - "docs"
- 'dependencies' - "dependencies"
- 'security' - "security"
exclude-labels: exclude-labels:
- 'skip-changelog' - "skip-changelog"
- 'no-changelog' - "no-changelog"
- 'changelog' - "changelog"
- 'bump versions' - "bump versions"
- 'reverted' - "reverted"
- 'invalid' - "invalid"
# 忽略特定文件
; path/to/specific-file.wxml
# 忽略特定目录下的所有 wxml
; temp/**/*.wxml
# 忽略所有以 .legacy. 开头的文件
; **/*.legacy.*
dist dist
dev-dist dev-dist
.local .local
...@@ -7,7 +15,7 @@ coverage ...@@ -7,7 +15,7 @@ coverage
CODEOWNERS CODEOWNERS
.nitro .nitro
.output .output
.github/workflows/codeql.yml
**/*.vue **/*.vue
**/*.js **/*.js
**/*.ts **/*.ts
......
...@@ -3,9 +3,7 @@ ...@@ -3,9 +3,7 @@
"ESLint": { "ESLint": {
"type": "stdio", "type": "stdio",
"command": "npx", "command": "npx",
"args": [ "args": ["@eslint/mcp@latest"]
"@eslint/mcp@latest"
]
} }
}, },
"inputs": [] "inputs": []
......
...@@ -254,5 +254,5 @@ ...@@ -254,5 +254,5 @@
"vue.server.hybridMode": true, "vue.server.hybridMode": true,
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"oxc.enable": false, "oxc.enable": false,
"cSpell.words": ["archiver", "axios", "dotenv", "isequal", "jspm", "napi", "nolebase", "rollup", "vitest"], "cSpell.words": ["archiver", "axios", "dotenv", "isequal", "jspm", "napi", "nolebase", "rollup", "vitest"]
} }
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
## 开发相关 ## 开发相关
### `dev` ### `dev`
启动开发服务器,运行所有包/应用的开发模式。 启动开发服务器,运行所有包/应用的开发模式。
```bash ```bash
...@@ -12,6 +13,7 @@ pnpm dev ...@@ -12,6 +13,7 @@ pnpm dev
``` ```
### `dev:docs` ### `dev:docs`
启动文档开发服务器。 启动文档开发服务器。
```bash ```bash
...@@ -19,6 +21,7 @@ pnpm dev:docs ...@@ -19,6 +21,7 @@ pnpm dev:docs
``` ```
### `preview` ### `preview`
预览构建后的应用。 预览构建后的应用。
```bash ```bash
...@@ -28,6 +31,7 @@ pnpm preview ...@@ -28,6 +31,7 @@ pnpm preview
## 构建相关 ## 构建相关
### `build` ### `build`
构建项目(使用 turbo-run,设置内存限制为 8GB)。 构建项目(使用 turbo-run,设置内存限制为 8GB)。
```bash ```bash
...@@ -35,6 +39,7 @@ pnpm build ...@@ -35,6 +39,7 @@ pnpm build
``` ```
### `build:all` ### `build:all`
构建所有项目(使用 turbo,设置内存限制为 8GB)。 构建所有项目(使用 turbo,设置内存限制为 8GB)。
```bash ```bash
...@@ -42,6 +47,7 @@ pnpm build:all ...@@ -42,6 +47,7 @@ pnpm build:all
``` ```
### `build:filter` ### `build:filter`
按过滤条件构建并复制到根目录。 按过滤条件构建并复制到根目录。
```bash ```bash
...@@ -49,6 +55,7 @@ pnpm build:filter ...@@ -49,6 +55,7 @@ pnpm build:filter
``` ```
### `build:docs` ### `build:docs`
构建文档项目。 构建文档项目。
```bash ```bash
...@@ -58,6 +65,7 @@ pnpm build:docs ...@@ -58,6 +65,7 @@ pnpm build:docs
## 代码质量检查 ## 代码质量检查
### `check` ### `check`
运行所有检查:循环依赖、依赖、类型检查、拼写检查。 运行所有检查:循环依赖、依赖、类型检查、拼写检查。
```bash ```bash
...@@ -65,6 +73,7 @@ pnpm check ...@@ -65,6 +73,7 @@ pnpm check
``` ```
### `check:circular` ### `check:circular`
检查代码中的循环依赖。 检查代码中的循环依赖。
```bash ```bash
...@@ -72,6 +81,7 @@ pnpm check:circular ...@@ -72,6 +81,7 @@ pnpm check:circular
``` ```
### `check:dep` ### `check:dep`
检查依赖关系。 检查依赖关系。
```bash ```bash
...@@ -79,6 +89,7 @@ pnpm check:dep ...@@ -79,6 +89,7 @@ pnpm check:dep
``` ```
### `check:type` ### `check:type`
运行 TypeScript 类型检查。 运行 TypeScript 类型检查。
```bash ```bash
...@@ -86,6 +97,7 @@ pnpm check:type ...@@ -86,6 +97,7 @@ pnpm check:type
``` ```
### `check:cspell` ### `check:cspell`
对代码和文档进行拼写检查。 对代码和文档进行拼写检查。
```bash ```bash
...@@ -93,6 +105,7 @@ pnpm check:cspell ...@@ -93,6 +105,7 @@ pnpm check:cspell
``` ```
### `lint` ### `lint`
运行 ESLint 代码检查。 运行 ESLint 代码检查。
```bash ```bash
...@@ -100,6 +113,7 @@ pnpm lint ...@@ -100,6 +113,7 @@ pnpm lint
``` ```
### `format` ### `format`
格式化代码(自动修复格式问题)。 格式化代码(自动修复格式问题)。
```bash ```bash
...@@ -107,6 +121,7 @@ pnpm format ...@@ -107,6 +121,7 @@ pnpm format
``` ```
### `publint` ### `publint`
发布前对包进行 lint 检查。 发布前对包进行 lint 检查。
```bash ```bash
...@@ -116,6 +131,7 @@ pnpm publint ...@@ -116,6 +131,7 @@ pnpm publint
## 测试相关 ## 测试相关
### `test:unit` ### `test:unit`
运行单元测试(使用 Vitest,DOM 环境)。 运行单元测试(使用 Vitest,DOM 环境)。
```bash ```bash
...@@ -123,6 +139,7 @@ pnpm test:unit ...@@ -123,6 +139,7 @@ pnpm test:unit
``` ```
### `test:e2e` ### `test:e2e`
运行端到端测试(使用 Playwright)。 运行端到端测试(使用 Playwright)。
```bash ```bash
...@@ -130,6 +147,7 @@ pnpm test:e2e ...@@ -130,6 +147,7 @@ pnpm test:e2e
``` ```
### `command:test` ### `command:test`
测试构建命令。 测试构建命令。
```bash ```bash
...@@ -139,6 +157,7 @@ pnpm command:test ...@@ -139,6 +157,7 @@ pnpm command:test
## 依赖管理 ## 依赖管理
### `update:deps` ### `update:deps`
交互式更新所有依赖到最新版本。 交互式更新所有依赖到最新版本。
```bash ```bash
...@@ -146,6 +165,7 @@ pnpm update:deps ...@@ -146,6 +165,7 @@ pnpm update:deps
``` ```
### `reinstall` ### `reinstall`
清理并重新安装依赖(删除锁文件后重新安装)。 清理并重新安装依赖(删除锁文件后重新安装)。
```bash ```bash
...@@ -153,6 +173,7 @@ pnpm reinstall ...@@ -153,6 +173,7 @@ pnpm reinstall
``` ```
### `clean` ### `clean`
清理构建产物和临时文件。 清理构建产物和临时文件。
```bash ```bash
...@@ -162,6 +183,7 @@ pnpm clean ...@@ -162,6 +183,7 @@ pnpm clean
## 版本管理 ## 版本管理
### `changeset` ### `changeset`
创建变更集(用于版本管理和生成 CHANGELOG)。 创建变更集(用于版本管理和生成 CHANGELOG)。
```bash ```bash
...@@ -169,6 +191,7 @@ pnpm changeset ...@@ -169,6 +191,7 @@ pnpm changeset
``` ```
### `version` ### `version`
更新版本号并更新锁文件(通常在发布前使用)。 更新版本号并更新锁文件(通常在发布前使用)。
```bash ```bash
...@@ -176,6 +199,7 @@ pnpm version ...@@ -176,6 +199,7 @@ pnpm version
``` ```
### `catalog` ### `catalog`
运行 pnpm catalog codemod(管理依赖目录)。 运行 pnpm catalog codemod(管理依赖目录)。
```bash ```bash
...@@ -185,6 +209,7 @@ pnpm catalog ...@@ -185,6 +209,7 @@ pnpm catalog
## Venus CLI 相关 ## Venus CLI 相关
### `venus` ### `venus`
运行 Venus CLI 工具。 运行 Venus CLI 工具。
```bash ```bash
...@@ -192,6 +217,7 @@ pnpm venus ...@@ -192,6 +217,7 @@ pnpm venus
``` ```
### `venus:build` ### `venus:build`
构建 Venus CLI 工具。 构建 Venus CLI 工具。
```bash ```bash
...@@ -199,6 +225,7 @@ pnpm venus:build ...@@ -199,6 +225,7 @@ pnpm venus:build
``` ```
### `venus:create` ### `venus:create`
创建新的 Venus 项目。 创建新的 Venus 项目。
```bash ```bash
...@@ -206,6 +233,7 @@ pnpm venus:create ...@@ -206,6 +233,7 @@ pnpm venus:create
``` ```
### `venus:create:interactive` ### `venus:create:interactive`
交互式创建新的 Venus 项目。 交互式创建新的 Venus 项目。
```bash ```bash
...@@ -213,6 +241,7 @@ pnpm venus:create:interactive ...@@ -213,6 +241,7 @@ pnpm venus:create:interactive
``` ```
### `venus:ls` ### `venus:ls`
列出可用的 Venus 模板。 列出可用的 Venus 模板。
```bash ```bash
...@@ -222,6 +251,7 @@ pnpm venus:ls ...@@ -222,6 +251,7 @@ pnpm venus:ls
## Git 相关 ## Git 相关
### `commit` ### `commit`
使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。 使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。
```bash ```bash
...@@ -231,11 +261,13 @@ pnpm commit ...@@ -231,11 +261,13 @@ pnpm commit
## 生命周期钩子 ## 生命周期钩子
### `preinstall` ### `preinstall`
安装前钩子:强制使用 pnpm 作为包管理器。 安装前钩子:强制使用 pnpm 作为包管理器。
### `postinstall` ### `postinstall`
安装后钩子:在所有包中运行 stub 脚本(如果存在)。 安装后钩子:在所有包中运行 stub 脚本(如果存在)。
### `prepare` ### `prepare`
初始化 Husky Git hooks。
初始化 Husky Git hooks。
...@@ -89,11 +89,13 @@ micro-app-template/ ...@@ -89,11 +89,13 @@ micro-app-template/
在启动前,请确保配置正确(已在本次更新中修复): 在启动前,请确保配置正确(已在本次更新中修复):
**子应用配置检查:** **子应用配置检查:**
- ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/` - ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/`
- ✅ `src/router/index.ts` - 导出 `createRouter` 函数 - ✅ `src/router/index.ts` - 导出 `createRouter` 函数
- ✅ `src/main.ts` - 动态创建路由实例 - ✅ `src/main.ts` - 动态创建路由实例
**基座配置检查:** **基座配置检查:**
- ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081` - ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081`
- ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>` - ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>`
...@@ -107,6 +109,7 @@ pnpm dev ...@@ -107,6 +109,7 @@ pnpm dev
子应用会在 `http://localhost:8081` 启动 子应用会在 `http://localhost:8081` 启动
**验证:** **验证:**
- 访问 `http://localhost:8081` 应显示子应用 - 访问 `http://localhost:8081` 应显示子应用
- 控制台显示 "独立运行模式" - 控制台显示 "独立运行模式"
...@@ -120,6 +123,7 @@ pnpm dev ...@@ -120,6 +123,7 @@ pnpm dev
基座会在 `http://localhost:8080` 启动 基座会在 `http://localhost:8080` 启动
**验证:** **验证:**
- 控制台显示 "[qiankun] 微前端框架已启动" - 控制台显示 "[qiankun] 微前端框架已启动"
### 3. 在基座中访问子应用 ### 3. 在基座中访问子应用
...@@ -127,6 +131,7 @@ pnpm dev ...@@ -127,6 +131,7 @@ pnpm dev
访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用 访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用
**预期结果:** **预期结果:**
- 看到子应用内容(紫色渐变背景) - 看到子应用内容(紫色渐变背景)
- 控制台显示生命周期日志 - 控制台显示生命周期日志
- 运行模式显示 "🔗 基座模式" - 运行模式显示 "🔗 基座模式"
...@@ -148,7 +153,7 @@ const PORT = 8081; // 修改为你想要的端口 ...@@ -148,7 +153,7 @@ const PORT = 8081; // 修改为你想要的端口
1. 在 `vite.config.ts` 中修改 `APP_NAME`: 1. 在 `vite.config.ts` 中修改 `APP_NAME`:
```typescript ```typescript
const APP_NAME = 'your-app-name'; const APP_NAME = "your-app-name";
``` ```
2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置: 2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置:
...@@ -203,12 +208,12 @@ pnpm dev ...@@ -203,12 +208,12 @@ pnpm dev
使用以下方式判断应用是否在 qiankun 环境中运行: 使用以下方式判断应用是否在 qiankun 环境中运行:
```typescript ```typescript
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'; import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('在基座中运行'); console.log("在基座中运行");
} else { } else {
console.log('独立运行'); console.log("独立运行");
} }
``` ```
...@@ -217,11 +222,13 @@ if (qiankunWindow.__POWERED_BY_QIANKUN__) { ...@@ -217,11 +222,13 @@ if (qiankunWindow.__POWERED_BY_QIANKUN__) {
### 1. 子应用无法加载(白屏) ### 1. 子应用无法加载(白屏)
**原因:** **原因:**
- 子应用未启动 - 子应用未启动
- entry 地址配置错误 - entry 地址配置错误
- 容器 ID 不存在 - 容器 ID 不存在
**解决:** **解决:**
```bash ```bash
# 确认子应用运行 # 确认子应用运行
curl http://localhost:8081 curl http://localhost:8081
...@@ -238,11 +245,13 @@ entry: 'http://localhost:8081' // ✅ 使用完整 URL ...@@ -238,11 +245,13 @@ entry: 'http://localhost:8081' // ✅ 使用完整 URL
### 2. CORS 错误 ### 2. CORS 错误
**控制台显示:** **控制台显示:**
``` ```
Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
``` ```
**解决:** **解决:**
- 确认子应用 `vite.config.ts` 中 `cors: true` - 确认子应用 `vite.config.ts` 中 `cors: true`
- 确认 headers 配置正确 - 确认 headers 配置正确
- 重启子应用服务 - 重启子应用服务
...@@ -250,15 +259,15 @@ Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy ...@@ -250,15 +259,15 @@ Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
### 3. 路由跳转异常 ### 3. 路由跳转异常
**原因:** **原因:**
- 路由 base 配置错误 - 路由 base 配置错误
- `routerBase` 未正确传递 - `routerBase` 未正确传递
**解决:** **解决:**
```typescript ```typescript
// ✅ 已修复:子应用动态创建路由 // ✅ 已修复:子应用动态创建路由
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ ? props.routerBase || "/subapp-vue" : "/";
? (props.routerBase || '/subapp-vue')
: '/';
const router = createRouter(routerBase); const router = createRouter(routerBase);
``` ```
...@@ -271,18 +280,20 @@ const router = createRouter(routerBase); ...@@ -271,18 +280,20 @@ const router = createRouter(routerBase);
### 5. 生命周期未触发 ### 5. 生命周期未触发
**原因:** **原因:**
- 应用名称不一致 - 应用名称不一致
- 生命周期钩子未正确导出 - 生命周期钩子未正确导出
**解决:** **解决:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
qiankun('subapp-vue') // 必须与基座配置一致 qiankun("subapp-vue"); // 必须与基座配置一致
// main.ts // main.ts
export async function bootstrap() { } export async function bootstrap() {}
export async function mount(props) { } export async function mount(props) {}
export async function unmount(props) { } export async function unmount(props) {}
``` ```
**详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md) **详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
...@@ -294,4 +305,3 @@ MIT ...@@ -294,4 +305,3 @@ MIT
## 🤝 贡献 ## 🤝 贡献
欢迎提交 Issue 和 Pull Request! 欢迎提交 Issue 和 Pull Request!
// / <reference types="vite/client" /> // / <reference types="vite/client" />
declare module '*.vue' { declare module "*.vue" {
import type { DefineComponent } from 'vue'; import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<Record<string, never>, Record<string, never>, any>;
export default component; export default component;
} }
......
<!doctype html> <!doctype html>
<html lang="zh-CN" sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;"> <html
<head> lang="zh-CN"
<meta charset="UTF-8" /> sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;">
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="UTF-8" />
<title></title> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head> <title></title>
<body> <meta name="description" content="" />
<div id="app"></div> </head>
<script type="module" src="/src/main.ts"></script> <body>
</body> <div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html> </html>
{ {
"name": "@venus/venus-agentic-assisant", "name": "@venus/venus-agentic-assisant",
"version": "1.0.0", "version": "1.0.0",
"description": "汽车智能体-智能助理", "description": "汽车智能体-智能助理",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --port 8081 --host", "dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build", "build": "vue-tsc && vite build",
"postbuild": "node ../../../../scripts/copy-dist-to-root.mjs", "postbuild": "node ../../../../scripts/copy-dist-to-root.mjs",
"preview": "vite preview --port 8081", "preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "catalog:", "@element-plus/icons-vue": "catalog:",
"@js-preview/docx": "catalog:", "@js-preview/docx": "catalog:",
"@js-preview/excel": "catalog:", "@js-preview/excel": "catalog:",
"@js-preview/pdf": "catalog:", "@js-preview/pdf": "catalog:",
"@venus/common-ui-vue": "workspace:*", "@venus/common-ui-vue": "workspace:*",
"@venus/tailwind-config": "workspace:*", "@venus/tailwind-config": "workspace:*",
"@venus/tools": "workspace:*", "@venus/tools": "workspace:*",
"@vue-office/docx": "catalog:", "@vue-office/docx": "catalog:",
"@vue-office/excel": "catalog:", "@vue-office/excel": "catalog:",
"@vue-office/pdf": "catalog:", "@vue-office/pdf": "catalog:",
"@vue-office/pptx": "catalog:", "@vue-office/pptx": "catalog:",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"axios": "catalog:", "axios": "catalog:",
"element-plus": "catalog:", "element-plus": "catalog:",
"glsk-oss-jssdk": "catalog:", "glsk-oss-jssdk": "catalog:",
"pinia": "catalog:", "glsk-toolkit": "catalog:",
"sass": "catalog:", "pinia": "catalog:",
"tailwindcss": "catalog:", "sass": "catalog:",
"vue": "catalog:", "tailwindcss": "catalog:",
"vue-router": "catalog:" "vue": "catalog:",
"vue-router": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "catalog:", "@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:", "@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:", "@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:", "typescript": "catalog:",
"unplugin-auto-import": "catalog:", "unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:", "unplugin-vue-components": "catalog:",
"vite": "catalog:", "vite": "catalog:",
"vite-plugin-qiankun": "catalog:", "vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:" "vue-tsc": "catalog:"
} }
} }
export { default } from '@venus/tailwind-config/postcss'; export { default } from "@venus/tailwind-config/postcss";
...@@ -18,17 +18,17 @@ onMounted(() => { ...@@ -18,17 +18,17 @@ onMounted(() => {
<style scoped> <style scoped>
.app-main { .app-main {
flex: 1; flex: 1;
} }
/* 路由过渡动画 */ /* 路由过渡动画 */
.fade-enter-active, .fade-enter-active,
.fade-leave-active { .fade-leave-active {
transition: opacity 0.3s ease; transition: opacity 0.3s ease;
} }
.fade-enter-from, .fade-enter-from,
.fade-leave-to { .fade-leave-to {
opacity: 0; opacity: 0;
} }
</style> </style>
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 质检规则列表查询 * 质检规则列表查询
*/ */
export async function inspectionRuleList(data: any) { export async function inspectionRuleList(data: any) {
try { return await gscPost("/inspectionRule/findPageInspectionRule", data);
const response = await gscPost('/inspectionRule/findPageInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则新增 * 质检规则新增
*/ */
export async function addInspectionRule(data: any) { export async function addInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/addInspectionRule", data);
const response = await gscPost('/inspectionRule/addInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则列表修改 * 质检规则列表修改
*/ */
export async function updateInspectionRule(data: any) { export async function updateInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/updateInspectionRule", data);
const response = await gscPost('/inspectionRule/updateInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则列表删除 * 质检规则列表删除
*/ */
export async function deleteInspectionRule(data: any) { export async function deleteInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/deleteInspectionRule", data);
const response = await gscPost('/inspectionRule/deleteInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版列表查询 * 质检模版列表查询
*/ */
export async function inspectionTemplateList(data: any) { export async function inspectionTemplateList(data: any) {
try { return await gscPost("/inspectionTemplate/findPageInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/findPageInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版新增 * 质检模版新增
*/ */
export async function addInspectionTemplate(data: any) { export async function addInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/saveInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/saveInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版修改 * 质检模版修改
*/ */
export async function updateInspectionTemplate(data: any) { export async function updateInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/updateInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/updateInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版删除 * 质检模版删除
*/ */
export async function deleteInspectionTemplate(data: any) { export async function deleteInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/deleteInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/deleteInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体列表查询 * 培训智能体列表查询
*/ */
export async function trainingPlanList(data: any) { export async function trainingPlanList(data: any) {
try { return await gscPost("/trainingPlan/findPageTrainingPlan", data);
const response = await gscPost('/trainingPlan/findPageTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体新增 * 培训智能体新增
*/ */
export async function addTrainingPlan(data: any) { export async function addTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/addTrainingPlan", data);
const response = await gscPost('/trainingPlan/addTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体修改 * 培训智能体修改
*/ */
export async function updateTrainingPlan(data: any) { export async function updateTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/updateTrainingPlan", data);
const response = await gscPost('/trainingPlan/updateTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体删除 * 培训智能体删除
*/ */
export async function deleteTrainingPlan(data: any) { export async function deleteTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/deleteTrainingPlan", data);
const response = await gscPost('/trainingPlan/deleteTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体详情 * 培训智能体详情
*/ */
export async function ftrainingPlanDetail(data: any) { export async function ftrainingPlanDetail(data: any) {
try { return await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
const response = await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 通用知识分类列表 * 通用知识分类列表
*/ */
export async function generalKnowledgeList(data: any) { export async function generalKnowledgeList(data: any) {
try { return await gscPost("/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList", data);
const response = await gscPost('/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList', data);
return response;
} catch (error) {
throw error;
}
} }
/* /*
* 复盘智能体提示词模板查询 * 复盘智能体提示词模板查询
*/ */
export async function getPromptTemplate(data: any) { export async function getPromptTemplate(data: any) {
try { return await gscPost("/reviewAgentPromptTemplate/findPromptTemplate", data);
const response = await gscPost('/reviewAgentPromptTemplate/findPromptTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/* /*
* 复盘智能体提示词模板更新 * 复盘智能体提示词模板更新
*/ */
export async function updatePromptTemplate(data: any) { export async function updatePromptTemplate(data: any) {
try { return await gscPost("/reviewAgentPromptTemplate/updatePromptTemplate", data);
const response = await gscPost('/reviewAgentPromptTemplate/updatePromptTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 岗位助理列表 * 岗位助理列表
*/ */
export async function assistantList(data: any) { export async function assistantList(data: any) {
try { return await gscPost("/jobAgentInfo/findPageAgentInfo", data);
const response = await gscPost('/jobAgentInfo/findPageAgentInfo', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理详情 * 岗位助理详情
*/ */
export async function assistantDetail(data: any) { export async function assistantDetail(data: any) {
try { return await gscPost("/jobAgentDetail/detailById", data);
const response = await gscPost('/jobAgentDetail/detailById', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理创建 * 岗位助理创建
*/ */
export async function assistantCreate(data: any) { export async function assistantCreate(data: any) {
try { return await gscPost("/jobAgentInfo/create", data);
const response = await gscPost('/jobAgentInfo/create', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理更新 * 岗位助理更新
*/ */
export async function assistantUpdate(data: any) { export async function assistantUpdate(data: any) {
try { return await gscPost("/jobAgentInfo/update", data);
const response = await gscPost('/jobAgentInfo/update', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理状态修改 * 岗位助理状态修改
*/ */
export async function assistantStatus(data: any) { export async function assistantStatus(data: any) {
try { return await gscPost("/jobAgentInfo/forbiddenOrEnable", data);
const response = await gscPost('/jobAgentInfo/forbiddenOrEnable', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 企微部门模块树 * 企微部门模块树
*/ */
export async function findDeptTree(data: any) { export async function findDeptTree(data: any) {
try { return await gscPost("/entmicroDepartment/findDeptTree", data);
const response = await gscPost('/entmicroDepartment/findDeptTree', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 素材分组列表 * 素材分组列表
*/ */
export async function findCategoryList(data: any) { export async function findCategoryList(data: any) {
try { return await gscPost("/knowledgeCategory/findCategoryList", data);
const response = await gscPost('/knowledgeCategory/findCategoryList', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材分组新增 * 素材分组新增
*/ */
export async function addCategory(data: any) { export async function addCategory(data: any) {
try { return await gscPost("/knowledgeCategory/addCategory", data, { returnAll:true });
const response = await gscPost('/knowledgeCategory/addCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材分组修改 * 素材分组修改
*/ */
export async function updateCategory(data: any) { export async function updateCategory(data: any) {
try { return await gscPost("/knowledgeCategory/updateCategory", data, { returnAll:true });
const response = await gscPost('/knowledgeCategory/updateCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 分组列表包含的素材列表 * 分组列表包含的素材列表
*/ */
export async function findCategoryWithMaterialList(data: any) { export async function findCategoryWithMaterialList(data: any) {
try { return await gscPost("/knowledgeCategory/findCategoryWithMaterialList", data);
const response = await gscPost('/knowledgeCategory/findCategoryWithMaterialList', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材列表 * 素材列表
*/ */
export async function findPageKnowledgeMaterial(data: any) { export async function findPageKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/findPageKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/findPageKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
...@@ -65,34 +40,19 @@ export async function findPageKnowledgeMaterial(data: any) { ...@@ -65,34 +40,19 @@ export async function findPageKnowledgeMaterial(data: any) {
* 素材编辑 * 素材编辑
*/ */
export async function updateKnowledgeMaterial(data: any) { export async function updateKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/updateKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/updateKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材上传 * 素材上传
*/ */
export async function saveKnowledgeMaterial(data: any) { export async function saveKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/saveKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/saveKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材删除 * 素材删除
*/ */
export async function deleteKnowledgeMaterial(data: any) { export async function deleteKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/deleteKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/deleteKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
...@@ -5,69 +5,69 @@ ...@@ -5,69 +5,69 @@
/* 全局样式 */ /* 全局样式 */
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
:root { :root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
font-weight: 400; font-weight: 400;
line-height: 1.5; line-height: 1.5;
color-scheme: light dark; color-scheme: light dark;
font-synthesis: none; font-synthesis: none;
text-rendering: optimizelegibility; text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
html, html,
body { body {
width: 100%; width: 100%;
height: 100%; height: 100%;
padding: 0; padding: 0;
margin: 0; margin: 0;
} }
body { body {
display: flex; display: flex;
place-items: center; place-items: center;
min-width: 320px; min-width: 320px;
min-height: 100vh; min-height: 100vh;
margin: 0; margin: 0;
} }
#app { #app {
width: 100%; width: 100%;
min-height: 100vh; min-height: 100vh;
} }
/* 滚动条样式 */ /* 滚动条样式 */
::-webkit-scrollbar { ::-webkit-scrollbar {
width: 8px; width: 8px;
height: 8px; height: 8px;
} }
::-webkit-scrollbar-track { ::-webkit-scrollbar-track {
background: rgb(255 255 255 / 10%); background: rgb(255 255 255 / 10%);
} }
::-webkit-scrollbar-thumb { ::-webkit-scrollbar-thumb {
background: rgb(255 255 255 / 30%); background: rgb(255 255 255 / 30%);
border-radius: 4px; border-radius: 4px;
} }
::-webkit-scrollbar-thumb:hover { ::-webkit-scrollbar-thumb:hover {
background: rgb(255 255 255 / 50%); background: rgb(255 255 255 / 50%);
} }
/* 选中文本样式 */ /* 选中文本样式 */
::selection { ::selection {
color: #2f3133; color: #2f3133;
background: #e3f2fd; background: #e3f2fd;
} }
/* 响应式 */ /* 响应式 */
@media (max-width: 768px) { @media (max-width: 768px) {
body { body {
font-size: 14px; font-size: 14px;
} }
} }
<template> <template>
<div class="card-list w-full flex flex-nowrap gap-6"> <div class="card-list w-full flex flex-nowrap gap-6">
<div <div v-for="(item, index) in data"
class="card-item flex-1 min-w-[202.5px] rounded-[10px] box-border shadow-[0_4px_12px_0_#525b6629]" :key="index"
:style="{ minHeight: cardHeight }" class="card-item flex-1 min-w-[202.5px] rounded-[10px] box-border shadow-[0_4px_12px_0_#525b6629]"
v-for="(item, index) in data" :style="{ minHeight: cardHeight }">
:key="index" <img alt="background"
> class="rounded-t-[10px]"
<img class="rounded-t-[10px]" :src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`" alt="background"> :src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`">
<div class="card-item-bottom h-[102.5px] w-full pl-[16px] pr-[16px]"> <div class="card-item-bottom h-[102.5px] w-full pl-[16px] pr-[16px]">
<p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] bg-red-500">{{ item.name }}</p> <p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] bg-red-500">
<div class="flex justify-between" v-for="value in item.desc"> {{ item.name }}
<p class="h-[6px] w-[6px] bg-[#1956FE] rounded-[3px] mt-[12px] mr-1"></p> </p>
<p class="w-full text-[#565C66] text-[12px] leading-[18px] mt-[6px]">{{value}}</p> <div v-for="value in item.desc"
:key="value"
class="flex justify-between">
<p class="h-[6px] w-[6px] bg-[#1956FE] rounded-[3px] mt-[12px] mr-1"></p>
<p class="w-full text-[#565C66] text-[12px] leading-[18px] mt-[6px]">
{{ value }}
</p>
</div>
</div>
</div> </div>
</div>
</div> </div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, PropType } from 'vue'; import { computed, PropType } from "vue";
interface DataItem { interface DataItem {
iconUrl: string; iconUrl: string;
...@@ -26,21 +32,21 @@ interface DataItem { ...@@ -26,21 +32,21 @@ interface DataItem {
desc: string[]; desc: string[];
} }
const props = defineProps({ const props = defineProps({
data: { data: {
type: Array as PropType<DataItem[]>, type: Array as PropType<DataItem[]>,
required: true, required: true,
}, },
source: { source: {
type: String as PropType<'train' | 'raplay' | 'other'>, type: String as PropType<"other" | "raplay" | "train">,
required: false, required: false,
default: 'other', default: "other",
}, },
}); });
const cardHeight = computed(() => { const cardHeight = computed(() => {
if (props.source === 'train') return '246px'; if (props.source === "train") return "246px";
if (props.source === 'raplay') return '204px'; if (props.source === "raplay") return "204px";
return '182px'; return "182px";
}); });
console.log('[CustomCardList] data', props.data); console.log("[CustomCardList] data", props.data);
</script> </script>
<template> <template>
<div class="flex align-center items-center h-[42px] mb-4"> <div class="flex align-center items-center h-[42px] mb-4">
<img src="/images/icon-title.png" alt="title" class="w-[4px] h-[18px] rounded-sm"> <img alt="title"
<p class="text-[14px] font-medium text-[#2F3133] ml-[12px]">{{ title }}</p> class="w-[4px] h-[18px] rounded-sm"
</div> src="/images/icon-title.png">
<p class="text-[14px] font-medium text-[#2F3133] ml-[12px]">
{{ title }}
</p>
</div>
</template> </template>
<script setup> <script setup>
const props = defineProps({ const props = defineProps({
title: { title: {
type: String, type: String,
required: true, required: true,
}, },
icon: { icon: {
type: String, type: String,
required: false, required: false,
}, default: "",
},
}); });
console.log(props.icon);
</script> </script>
<template> <template>
<div class="pl-2"> <div class="pl-2">
<div <div v-for="(item, index) in workflowSteps"
v-for="(item, index) in workflowSteps" :key="index"
:key="index" class="relative pb-8 last:pb-0">
class="relative pb-8 last:pb-0" <!-- 连接线 -->
> <div v-if="index !== workflowSteps.length - 1"
<!-- 连接线 --> aria-hidden="true"
<div class="absolute left-3.5 top-8 -ml-px h-full w-[2px] bg-gray-200">
v-if="index !== workflowSteps.length - 1" </div>
class="absolute left-3.5 top-8 -ml-px h-full w-[2px] bg-gray-200"
aria-hidden="true"
></div>
<div class="group relative flex items-start"> <div class="group relative flex items-start">
<!-- 步骤数字 --> <!-- 步骤数字 -->
<span <span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-50 ring-4 ring-white">
class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-50 ring-4 ring-white" <span class="text-sm font-bold text-blue-600">{{ index + 1 }}</span>
> </span>
<span class="text-sm font-bold text-blue-600">{{ index + 1 }}</span> <!-- 步骤内容 -->
</span> <div class="ml-4 min-w-0 flex-1">
<!-- 步骤内容 --> <h4 class="mb-1 text-[14px] font-normal text-[#2F3133]">
<div class="ml-4 min-w-0 flex-1"> {{ item.title }}
<h4 class="mb-1 text-[14px] font-normal text-[#2F3133]"> </h4>
{{ item.title }} <div v-if="Array.isArray(item.desc)">
</h4> <p v-for="value in item.desc"
<div v-if="Array.isArray(item.desc)"> :key="value"
<p class="mt-[4px] text-[12px] font-normal text-[#969AA3]">
class="mt-[4px] text-[12px] font-normal text-[#969AA3]" <span class="mb-[2px] mr-[4px] inline-block h-[5px] w-[5px] rounded-[3px] bg-[#1956FE]">
v-for="value in item.desc" </span>
> {{ value }}
<span </p>
class="mb-[2px] mr-[4px] inline-block h-[5px] w-[5px] rounded-[3px] bg-[#1956FE]" </div>
></span> <div v-else>
{{ value }} <p class="mt-[4px] text-[12px] font-normal text-[#969AA3]">
</p> {{ item.desc }}
</div> </p>
<div v-else> </div>
<p class="mt-[4px] text-[12px] font-normal text-[#969AA3]"> </div>
{{ item.desc }} </div>
</p>
</div>
</div> </div>
</div>
</div> </div>
</div>
</template> </template>
<script setup> <script setup>
import { defineProps } from 'vue'; import { defineProps } from "vue";
const props = defineProps({ const props = defineProps({
workflowSteps: { workflowSteps: {
type: Array, type: Array,
required: true, required: true,
}, },
}); });
</script> </script>
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper'; import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";
import type { App as VueApp } from "vue";
import { createApp } from "vue";
import CommonUI from "@venus/common-ui-vue";
import ElementPlus from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn"; import zhCn from "element-plus/es/locale/lang/zh-cn";
import type { App as VueApp } from 'vue';
import { createApp } from 'vue';
import ElementPlus from 'element-plus';
// import './styles/element/index.scss'; // import './styles/element/index.scss';
import { createPinia } from 'pinia'; import { createPinia } from "pinia";
import { import {
qiankunWindow, qiankunWindow,
renderWithQiankun, renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper'; } from "vite-plugin-qiankun/dist/helper";
import CommonUI from '@venus/common-ui-vue';
import App from './App.vue'; import App from "./App.vue";
import { createRouter } from './router'; import { createRouter } from "./router";
import 'element-plus/dist/index.css'; import "element-plus/dist/index.css";
import './assets/style.css'; import "./assets/style.css";
let app: null | VueApp<Element> = null; let app: null | VueApp<Element> = null;
let router: any = null; let router: any = null;
...@@ -25,63 +29,63 @@ let router: any = null; ...@@ -25,63 +29,63 @@ let router: any = null;
* @param props qiankun 传递的参数 * @param props qiankun 传递的参数
*/ */
async function render(props: QiankunProps = {}) { async function render(props: QiankunProps = {}) {
const { container } = props; const { container } = props;
app = createApp(App); app = createApp(App);
// 注册通用 UI 组件库 // 注册通用 UI 组件库
app.use(CommonUI); app.use(CommonUI);
// 配置 Pinia // 配置 Pinia
app.use(createPinia()); app.use(createPinia());
// 配置 Element-Plus // 配置 Element-Plus
app.use(ElementPlus, { app.use(ElementPlus, {
//改中文 // 改中文
locale: zhCn locale: zhCn
}); });
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base // 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? props.routerBase || '/assisant/' ? props.routerBase || "/assisant/"
: '/'; : "/";
router = createRouter(routerBase); router = createRouter(routerBase);
app.use(router); app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中) // 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) { if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.init(props); subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用 // 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication; app.config.globalProperties.$communication = subAppCommunication;
} }
// 初始化 GSC Request(仅在 qiankun 环境中) // 初始化 GSC Request(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.getGscRequest) { if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.getGscRequest) {
try { try {
const { gscRequestManager } = await import('./utils/gscRequest'); const { gscRequestManager } = await import("./utils/gscRequest");
await gscRequestManager.init(props); await gscRequestManager.init(props);
// 将 GSC Request 管理器挂载到全局属性,方便组件使用 // 将 GSC Request 管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$gscRequest = gscRequestManager; app.config.globalProperties.$gscRequest = gscRequestManager;
// console.log('[子应用] GSC Request 管理器已初始化并挂载'); // console.log('[子应用] GSC Request 管理器已初始化并挂载');
} catch (error) { } catch (error) {
console.error('[子应用] GSC Request 管理器初始化失败:', error); console.error("[子应用] GSC Request 管理器初始化失败:", error);
} }
} }
// 挂载应用 // 挂载应用
const containerEl = container const containerEl = container
? container.querySelector('#app') ? container.querySelector("#app")
: document.querySelector('#app'); : document.querySelector("#app");
if (containerEl) { if (containerEl) {
app.mount(containerEl as Element); app.mount(containerEl as Element);
} else { } else {
console.error('[Vue3 微应用] 挂载容器未找到'); console.error("[Vue3 微应用] 挂载容器未找到");
} }
} }
/** /**
...@@ -89,7 +93,7 @@ async function render(props: QiankunProps = {}) { ...@@ -89,7 +93,7 @@ async function render(props: QiankunProps = {}) {
* 直接访问子应用时,不是通过基座加载 * 直接访问子应用时,不是通过基座加载
*/ */
if (!qiankunWindow.__POWERED_BY_QIANKUN__) { if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
render(); render();
} }
/** /**
...@@ -97,7 +101,7 @@ if (!qiankunWindow.__POWERED_BY_QIANKUN__) { ...@@ -97,7 +101,7 @@ if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
* 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子 * 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子
*/ */
export async function bootstrap() { export async function bootstrap() {
// console.log('[Vue3 微应用钩子] bootstrap'); // console.log('[Vue3 微应用钩子] bootstrap');
} }
/** /**
...@@ -105,8 +109,8 @@ export async function bootstrap() { ...@@ -105,8 +109,8 @@ export async function bootstrap() {
* 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法 * 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法
*/ */
export async function mount(props: QiankunProps) { export async function mount(props: QiankunProps) {
// console.log('Vue3 微应用钩子 mount', props); // console.log('Vue3 微应用钩子 mount', props);
render(props); render(props);
} }
/** /**
...@@ -114,24 +118,24 @@ export async function mount(props: QiankunProps) { ...@@ -114,24 +118,24 @@ export async function mount(props: QiankunProps) {
* 应用每次切出/卸载都会调用 unmount 方法 * 应用每次切出/卸载都会调用 unmount 方法
*/ */
export async function unmount(props: QiankunProps) { export async function unmount(props: QiankunProps) {
console.log('[子应用] unmount', props); console.log("[子应用] unmount", props);
// 销毁通信管理器 // 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.destroy(); subAppCommunication.destroy();
// 销毁 GSC Request 管理器 // 销毁 GSC Request 管理器
const { gscRequestManager } = await import('./utils/gscRequest'); const { gscRequestManager } = await import("./utils/gscRequest");
gscRequestManager.destroy(); gscRequestManager.destroy();
} }
if (app) { if (app) {
app.unmount(); app.unmount();
app = null; app = null;
} }
if (router) { if (router) {
router = null; router = null;
} }
} }
/** /**
...@@ -139,13 +143,13 @@ export async function unmount(props: QiankunProps) { ...@@ -139,13 +143,13 @@ export async function unmount(props: QiankunProps) {
* 主应用向子应用下发新的props时触发 * 主应用向子应用下发新的props时触发
*/ */
export async function update(props: QiankunProps) { export async function update(props: QiankunProps) {
console.log('[Vue3 微应用] update', props); console.log("[Vue3 微应用] update", props);
} }
// 使用 vite-plugin-qiankun 提供的渲染函数 // 使用 vite-plugin-qiankun 提供的渲染函数
renderWithQiankun({ renderWithQiankun({
bootstrap, bootstrap,
mount, mount,
unmount, unmount,
update, update,
}); });
// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: 2026/1/23 10:58:16
import type { RouteRecordRaw } from 'vue-router';
export const autoRoutes: RouteRecordRaw[] = [
{
path: "/assistant/index",
id: "assistant",
title: "Assistant",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "assistant",
"keepAlive": false,
"requiresAuth": false,
"title": "Assistant"
},
children: [
{
path: "add-update",
id: "assistant-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "assistant:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/manage-agentic/index",
id: "manage-agentic",
title: "ManageAgentic",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "manage-agentic",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageAgentic"
},
},
{
path: "/manage-konw/index",
id: "manage-konw",
title: "ManageKonw",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "manage-konw",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageKonw"
},
children: [
{
path: "add-update",
id: "manage-konw-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "manage-konw:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/communication",
id: ".-communication",
title: "Communication",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "communication",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Communication"
},
},
{
path: "/home",
id: ".-home",
title: "Home",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "home",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Home"
},
},
{
path: "/settings",
id: ".-settings",
title: "Settings",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "settings",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Settings"
},
},
{
path: "/user",
id: ".-user",
title: "User",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "user",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "User"
},
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/NotFound.vue"),
meta: {
"title": "404",
"hidden": true
},
}
];
import type { Router, RouteRecordRaw, RouterOptions } from 'vue-router'; import type { Router, RouteRecordRaw, RouterOptions } from "vue-router";
import { createRouter as _createRouter, createWebHistory } from 'vue-router'; import { createRouter as _createRouter, createWebHistory } from "vue-router";
// 手动配置的路由 // 手动配置的路由
// 注意:auto-routes.ts 文件仅作为示例,不在项目中使用 // 注意:auto-routes.ts 文件仅作为示例,不在项目中使用
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
{ {
path: '/', path: "/",
name: 'Home', name: "Home",
component: () => import('@/views/Home.vue'), component: () => import("@/views/Home.vue"),
meta: { meta: {
title: '首页', title: "首页",
}, },
}, },
{ {
path: '/managekonw', path: "/managekonw",
name: 'ManageKonw', name: "ManageKonw",
component: () => import('@/views/ManageKonw/index.vue'), component: () => import("@/views/ManageKonw/index.vue"),
meta: { meta: {
title: '知识管理', title: "知识管理",
}, },
}, },
{ {
path: '/assistant', path: "/assistant",
name: 'Assistant', name: "Assistant",
component: () => import('@/views/Assistant/index.vue'), component: () => import("@/views/Assistant/index.vue"),
meta: { meta: {
title: '岗位助理配置', title: "岗位助理配置",
}, },
}, },
{ {
path: '/manageagentic', path: "/manageagentic",
name: 'ManageAgentic', name: "ManageAgentic",
component: () => import('@/views/ManageAgentic/index.vue'), component: () => import("@/views/ManageAgentic/index.vue"),
meta: { meta: {
title: '智能体管理', title: "智能体管理",
}, },
}, },
{ {
path: '/assistant/add', path: "/assistant/add",
name: 'AssistantAdd', name: "AssistantAdd",
component: () => import('@/views/Assistant/addUpdate.vue'), component: () => import("@/views/Assistant/addUpdate.vue"),
meta: { meta: {
title: '新增智能体', title: "新增智能体",
}, },
}, },
{ {
path: '/assistant/edit/:id', path: "/assistant/edit/:id",
name: 'AssistantEdit', name: "AssistantEdit",
component: () => import('@/views/Assistant/addUpdate.vue'), component: () => import("@/views/Assistant/addUpdate.vue"),
meta: { meta: {
title: '编辑', title: "编辑",
}, },
}, },
{ {
path: '/user', path: "/user",
name: 'User', name: "User",
component: () => import('@/views/User.vue'), component: () => import("@/views/User.vue"),
meta: { meta: {
title: '用户管理', title: "用户管理",
}, },
}, },
{ {
path: '/settings', path: "/settings",
name: 'Settings', name: "Settings",
component: () => import('@/views/Settings.vue'), component: () => import("@/views/Settings.vue"),
meta: { meta: {
title: '系统设置', title: "系统设置",
}, },
}, },
{ {
path: '/communication', path: "/communication",
name: 'Communication', name: "Communication",
component: () => import('@/views/Communication.vue'), component: () => import("@/views/Communication.vue"),
meta: { meta: {
title: '通信示例', title: "通信示例",
}, },
}, },
{ {
path: '/:pathMatch(.*)*', path: "/:pathMatch(.*)*",
name: 'NotFound', name: "NotFound",
component: () => import('@/views/NotFound.vue'), component: () => import("@/views/NotFound.vue"),
}, },
]; ];
// 转换为 RouterOptions 需要的类型 // 转换为 RouterOptions 需要的类型
const routerRoutes = routes as unknown as RouterOptions['routes']; const routerRoutes = routes as unknown as RouterOptions["routes"];
/** /**
* 创建路由实例 * 创建路由实例
* @param base 路由 base 路径 * @param base 路由 base 路径
*/ */
export function createRouter(base: string = '/'): Router { export function createRouter(base: string = "/"): Router {
const router = _createRouter({ const router = _createRouter({
history: createWebHistory(base), history: createWebHistory(base),
routes: routerRoutes, routes: routerRoutes,
}); });
// 路由守卫 // 路由守卫
router.beforeEach((to, _from, next) => { router.beforeEach((to, _from, next) => {
// 设置页面标题 // 设置页面标题
if (to.meta.title) { if (to.meta.title) {
document.title = `${to.meta.title}`; document.title = `${to.meta.title}`;
} }
next(); next();
}); });
router.afterEach((to, from) => { router.afterEach((to, from) => {
console.log('[Vue3 微应用] 路由切换:', from.path, '->', to.path); console.log("[Vue3 微应用] 路由切换:", from.path, "->", to.path);
}); });
return router; return router;
} }
@forward 'element-plus/theme-chalk/src/common/var.scss' with ( @forward "element-plus/theme-chalk/src/common/var.scss" with (
// $button: ( $colors: (
// "color": #666666, "primary": (
// "border-color": #E1E3E6, "base": #3d6eff,
// "hover-bg-color": #3d6eff, ),
// "hover-text-color": #ffffff, )
// "hover-border-color": #3d6eff,
// )
$colors: (
'primary': (
'base': #3d6eff,
)
)
); );
@use 'element-plus/theme-chalk/src/index.scss' as *; @use "element-plus/theme-chalk/src/index.scss" as *;
/** /**
* glsk-oss-jssdk 类型声明 * glsk-oss-jssdk 类型声明
*/ */
declare module 'glsk-oss-jssdk' { declare module "glsk-oss-jssdk" {
/** /**
* 上传结果接口 * 上传结果接口
*/ */
...@@ -18,13 +18,13 @@ declare module 'glsk-oss-jssdk' { ...@@ -18,13 +18,13 @@ declare module 'glsk-oss-jssdk' {
* OSS API 类 * OSS API 类
*/ */
class GlOssApi { class GlOssApi {
/** /**
* 分片上传文件 * 分片上传文件
* @param file 要上传的文件 * @param file 要上传的文件
* @param onSuccess 成功回调函数 * @param onSuccess 成功回调函数
* @param onError 失败回调函数 * @param onError 失败回调函数
*/ */
multipartUpload( multipartUpload(
file: File, file: File,
onSuccess: (result: MultipartUploadResult) => void, onSuccess: (result: MultipartUploadResult) => void,
onError: (error: Error) => void, onError: (error: Error) => void,
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
* 扩展 Vue Router 的 RouteRecordRaw 接口,支持自定义字段 * 扩展 Vue Router 的 RouteRecordRaw 接口,支持自定义字段
*/ */
import 'vue-router'; import "vue-router";
declare module 'vue-router' { declare module "vue-router" {
interface RouteRecordRaw { interface RouteRecordRaw {
/** 路由唯一标识 */ /** 路由唯一标识 */
id?: string; id?: string;
......
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'; import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
/** /**
* 获取子应用的基础 URL * 获取子应用的基础 URL
...@@ -11,53 +11,53 @@ import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'; ...@@ -11,53 +11,53 @@ import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
* 在独立运行时,返回当前域名 * 在独立运行时,返回当前域名
*/ */
export function getSubAppBaseUrl(): string { export function getSubAppBaseUrl(): string {
// 如果在 qiankun 环境中 // 如果在 qiankun 环境中
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
// qiankun 会注入 __INJECTED_PUBLIC_PATH_BY_QIANKUN__,包含子应用的公共路径 // qiankun 会注入 __INJECTED_PUBLIC_PATH_BY_QIANKUN__,包含子应用的公共路径
const publicPath = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; const publicPath = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
if (publicPath) { if (publicPath) {
// 从 publicPath 中提取基础 URL // 从 publicPath 中提取基础 URL
try { try {
// 尝试将 publicPath 解析为完整 URL // 尝试将 publicPath 解析为完整 URL
const url = new URL(publicPath); const url = new URL(publicPath);
// 如果 publicPath 是完整 URL(包含协议),返回其 origin // 如果 publicPath 是完整 URL(包含协议),返回其 origin
if (url.protocol.startsWith('http')) { if (url.protocol.startsWith("http")) {
return url.origin; return url.origin;
} }
} catch { } catch {
// URL 解析失败,说明 publicPath 可能是相对路径,继续下面的处理 // URL 解析失败,说明 publicPath 可能是相对路径,继续下面的处理
} }
// 在开发环境中,子应用通常运行在独立端口(如 8081) // 在开发环境中,子应用通常运行在独立端口(如 8081)
const isDev = (import.meta as any).env?.MODE === 'development'; const isDev = (import.meta as any).env?.MODE === "development";
if (isDev) { if (isDev) {
// 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致) // 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致)
const devPort = '8081'; const devPort = "8081";
const host = window.location.hostname; const host = window.location.hostname;
return `http://${host}:${devPort}`; return `http://${host}:${devPort}`;
} }
// 生产环境:如果 publicPath 是相对路径,说明可能是同域部署 // 生产环境:如果 publicPath 是相对路径,说明可能是同域部署
// 此时使用当前域名即可(资源应该在同一域名下) // 此时使用当前域名即可(资源应该在同一域名下)
return window.location.origin; return window.location.origin;
} }
// 如果无法从 publicPath 获取,根据环境判断 // 如果无法从 publicPath 获取,根据环境判断
const isDev = (import.meta as any).env?.MODE === 'development'; const isDev = (import.meta as any).env?.MODE === "development";
if (isDev) { if (isDev) {
// 开发环境:使用默认端口 // 开发环境:使用默认端口
const host = window.location.hostname; const host = window.location.hostname;
return `http://${host}:8081`; return `http://${host}:8081`;
} }
// 生产环境:使用当前域名 // 生产环境:使用当前域名
return window.location.origin; return window.location.origin;
} }
// 独立运行时,返回当前域名 // 独立运行时,返回当前域名
return window.location.origin; return window.location.origin;
} }
/** /**
...@@ -66,39 +66,39 @@ export function getSubAppBaseUrl(): string { ...@@ -66,39 +66,39 @@ export function getSubAppBaseUrl(): string {
* @returns 处理后的完整图片 URL * @returns 处理后的完整图片 URL
*/ */
export function getImageUrl(imagePath: string): string { export function getImageUrl(imagePath: string): string {
if (!imagePath) { if (!imagePath) {
return ''; return "";
} }
// 如果已经是完整的 URL(包含 http:// 或 https://),直接返回 // 如果已经是完整的 URL(包含 http:// 或 https://),直接返回
if (/^https?:\/\//.test(imagePath)) { if (/^https?:\/\//.test(imagePath)) {
// 如果是完整 URL,检查是否是子应用的域名 // 如果是完整 URL,检查是否是子应用的域名
try { try {
const url = new URL(imagePath); const url = new URL(imagePath);
const baseUrl = getSubAppBaseUrl(); const baseUrl = getSubAppBaseUrl();
const baseUrlObj = new URL(baseUrl, window.location.href); const baseUrlObj = new URL(baseUrl, window.location.href);
// 如果 URL 的域名和子应用的域名不同,需要替换为子应用的域名 // 如果 URL 的域名和子应用的域名不同,需要替换为子应用的域名
if (url.origin !== baseUrlObj.origin) { if (url.origin !== baseUrlObj.origin) {
// 提取路径部分,使用子应用的域名 // 提取路径部分,使用子应用的域名
return `${baseUrlObj.origin}${url.pathname}${url.search}${url.hash}`; return `${baseUrlObj.origin}${url.pathname}${url.search}${url.hash}`;
} }
return imagePath; return imagePath;
} catch { } catch {
return imagePath; return imagePath;
} }
} }
// 如果是相对路径(以 / 开头),拼接子应用的基础 URL // 如果是相对路径(以 / 开头),拼接子应用的基础 URL
if (imagePath.startsWith('/')) { if (imagePath.startsWith("/")) {
const baseUrl = getSubAppBaseUrl(); const baseUrl = getSubAppBaseUrl();
return `${baseUrl}${imagePath}`; return `${baseUrl}${imagePath}`;
} }
// 如果是相对路径(不以 / 开头),需要根据当前路径处理 // 如果是相对路径(不以 / 开头),需要根据当前路径处理
// 这里假设是相对于 public 目录的路径 // 这里假设是相对于 public 目录的路径
const baseUrl = getSubAppBaseUrl(); const baseUrl = getSubAppBaseUrl();
return `${baseUrl}/${imagePath}`; return `${baseUrl}/${imagePath}`;
} }
import { onUnmounted } from 'vue'; import { onUnmounted } from "vue";
/** /**
* 全局状态接口定义(与基座保持一致) * 全局状态接口定义(与基座保持一致)
...@@ -12,7 +12,7 @@ export interface GlobalState { ...@@ -12,7 +12,7 @@ export interface GlobalState {
notifications: Notification[]; notifications: Notification[];
theme: { theme: {
mode: 'dark' | 'light'; mode: "dark" | "light";
primaryColor: string; primaryColor: string;
}; };
...@@ -34,7 +34,7 @@ export interface Notification { ...@@ -34,7 +34,7 @@ export interface Notification {
message: string; message: string;
timestamp: number; timestamp: number;
title: string; title: string;
type: 'error' | 'info' | 'success' | 'warning'; type: "error" | "info" | "success" | "warning";
} }
/** /**
...@@ -55,117 +55,117 @@ export interface QiankunProps { ...@@ -55,117 +55,117 @@ export interface QiankunProps {
* 子应用通信管理器 * 子应用通信管理器
*/ */
class SubAppCommunicationManager { class SubAppCommunicationManager {
private currentState: GlobalState | null = null; // 缓存当前状态 private currentState: GlobalState | null = null; // 缓存当前状态
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> = private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[]; [];
private props: null | QiankunProps = null; private props: null | QiankunProps = null;
private unsubscribe: (() => void) | null = null; private unsubscribe: (() => void) | null = null;
/** /**
* 销毁 * 销毁
*/ */
destroy() { destroy() {
if (this.unsubscribe) { if (this.unsubscribe) {
this.unsubscribe(); this.unsubscribe();
this.unsubscribe = null; this.unsubscribe = null;
} }
this.listeners = []; this.listeners = [];
this.props = null; this.props = null;
} }
/** /**
* 获取当前全局状态 * 获取当前全局状态
*/ */
getCurrentState(): GlobalState | null { getCurrentState(): GlobalState | null {
return this.currentState; return this.currentState;
} }
/** /**
* 初始化通信管理器 * 初始化通信管理器
* @param props qiankun 传递的 props * @param props qiankun 传递的 props
*/ */
init(props: QiankunProps) { init(props: QiankunProps) {
this.props = props; this.props = props;
// 监听全局状态变化 // 监听全局状态变化
if (props.onGlobalStateChange) { if (props.onGlobalStateChange) {
const unsubscribeFn = props.onGlobalStateChange( const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => { (state: GlobalState, prev: GlobalState) => {
// 缓存当前状态 // 缓存当前状态
this.currentState = state; this.currentState = state;
// 触发所有监听器 // 触发所有监听器
this.listeners.forEach((listener) => { this.listeners.forEach((listener) => {
listener(state, prev); listener(state, prev);
}); });
}, },
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据 true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
); );
// 只在返回值是函数时才赋值 // 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') { if (typeof unsubscribeFn === "function") {
this.unsubscribe = unsubscribeFn; this.unsubscribe = unsubscribeFn;
} }
} }
} }
/** /**
* 监听全局状态变化 * 监听全局状态变化
* @param callback 回调函数 * @param callback 回调函数
* @returns 取消监听的函数 * @returns 取消监听的函数
*/ */
onStateChange( onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void, callback: (state: GlobalState, prev: GlobalState) => void,
): () => void { ): () => void {
this.listeners.push(callback); this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调 // 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) { if (this.currentState) {
callback(this.currentState, {} as GlobalState); callback(this.currentState, {} as GlobalState);
} }
return () => { return () => {
const index = this.listeners.indexOf(callback); const index = this.listeners.indexOf(callback);
if (index !== -1) { if (index !== -1) {
this.listeners.splice(index, 1); this.listeners.splice(index, 1);
} }
}; };
} }
/** /**
* 向基座发送通知 * 向基座发送通知
* @param notification 通知消息 * @param notification 通知消息
*/ */
sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) { sendNotification(notification: Omit<Notification, "id" | "timestamp">) {
if (!this.props?.setGlobalState) { if (!this.props?.setGlobalState) {
return; return;
} }
// 获取当前通知列表(需要通过 props 或缓存获取) // 获取当前通知列表(需要通过 props 或缓存获取)
// 这里简化处理,直接通过 state 添加 // 这里简化处理,直接通过 state 添加
const newNotification: Notification = { const newNotification: Notification = {
...notification, ...notification,
id: Date.now().toString(), id: Date.now().toString(),
timestamp: Date.now(), timestamp: Date.now(),
from: notification.from || 'Vue子应用', from: notification.from || "Vue子应用",
}; };
// 通过修改全局状态来添加通知 // 通过修改全局状态来添加通知
// 注意:这里需要基座的 communication manager 来处理通知添加逻辑 // 注意:这里需要基座的 communication manager 来处理通知添加逻辑
// 所以我们实际上是触发一个状态变化,让基座来处理 // 所以我们实际上是触发一个状态变化,让基座来处理
this.setGlobalState({ this.setGlobalState({
notifications: [newNotification] as any, // 基座会合并到现有通知列表 notifications: [ newNotification ] as any, // 基座会合并到现有通知列表
}); });
} }
/** /**
* 设置全局状态(向基座发送数据) * 设置全局状态(向基座发送数据)
* @param state 要更新的状态 * @param state 要更新的状态
*/ */
setGlobalState(state: Partial<GlobalState>) { setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) { if (this.props?.setGlobalState) {
this.props.setGlobalState(state); this.props.setGlobalState(state);
} }
} }
} }
// 导出单例 // 导出单例
...@@ -176,29 +176,29 @@ export const subAppCommunication = new SubAppCommunicationManager(); ...@@ -176,29 +176,29 @@ export const subAppCommunication = new SubAppCommunicationManager();
* @param callback 状态变化回调 * @param callback 状态变化回调
*/ */
export function useGlobalState( export function useGlobalState(
callback: (state: GlobalState, prev: GlobalState) => void, callback: (state: GlobalState, prev: GlobalState) => void,
) { ) {
const unsubscribe = subAppCommunication.onStateChange(callback); const unsubscribe = subAppCommunication.onStateChange(callback);
// 在组件卸载时自动取消订阅 // 在组件卸载时自动取消订阅
onUnmounted(() => { onUnmounted(() => {
unsubscribe(); unsubscribe();
}); });
return unsubscribe; return unsubscribe;
} }
/** /**
* 便捷方法:发送通知到基座 * 便捷方法:发送通知到基座
*/ */
export function notify( export function notify(
type: Notification['type'], type: Notification["type"],
title: string, title: string,
message: string, message: string,
) { ) {
subAppCommunication.sendNotification({ subAppCommunication.sendNotification({
type, type,
title, title,
message, message,
}); });
} }
import type { Request } from 'glsk-toolkit'; import type { Request } from "glsk-toolkit";
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper'; import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
/** /**
* GSC Request 管理器 * GSC Request 管理器
* 用于管理从基座获取的 Request 实例 * 用于管理从基座获取的 Request 实例
*/ */
class GscRequestManager { class GscRequestManager {
private requestInstance: Request | null = null; private getGscRequestFn: (() => Promise<Request>) | null = null;
private getGscRequestFn: (() => Promise<Request>) | null = null; private initPromise: null | Promise<Request> = null;
private initPromise: Promise<Request> | null = null; private requestInstance: null | Request = null;
/** /**
* 初始化 GSC Request(在子应用 render 函数中调用) * 销毁管理器
* @param props qiankun 传递的 props
*/ */
async init(props: QiankunProps) { destroy() {
if (!qiankunWindow.__POWERED_BY_QIANKUN__) { this.requestInstance = null;
console.warn('[GSC Request] 非 qiankun 环境,无法获取 Request 实例'); this.getGscRequestFn = null;
return; this.initPromise = null;
} }
if (!props.getGscRequest) { /**
console.warn('[GSC Request] props 中未找到 getGscRequest 函数');
return;
}
this.getGscRequestFn = props.getGscRequest;
try {
if (this.getGscRequestFn) {
this.requestInstance = await this.getGscRequestFn();
}
} catch (error) {
console.error('[GSC Request] 实例初始化失败:', error);
throw error;
}
}
/**
* 获取 GSC Request 实例 * 获取 GSC Request 实例
* @returns Promise<Request> Request 实例 * @returns Promise<Request> Request 实例
*/ */
async getRequest(): Promise<Request> { async getRequest(): Promise<Request> {
// 如果已有实例,直接返回 // 如果已有实例,直接返回
if (this.requestInstance) { if (this.requestInstance) {
return this.requestInstance; return this.requestInstance;
} }
// 如果有获取函数,尝试获取 // 如果有获取函数,尝试获取
if (this.getGscRequestFn) { if (this.getGscRequestFn) {
// 如果正在初始化,等待初始化完成 // 如果正在初始化,等待初始化完成
if (this.initPromise) { if (this.initPromise) {
return this.initPromise; return this.initPromise;
} }
// 创建初始化 Promise // 创建初始化 Promise
this.initPromise = this.getGscRequestFn().then((instance) => { this.initPromise = this.getGscRequestFn().then((instance) => {
this.requestInstance = instance; this.requestInstance = instance;
this.initPromise = null; this.initPromise = null;
return instance; return instance;
}); });
return this.initPromise; return this.initPromise;
} }
throw new Error( throw new Error(
'[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法', "[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法",
); );
} }
/** /**
* 检查 Request 是否已初始化 * 初始化 GSC Request(在子应用 render 函数中调用)
* @param props qiankun 传递的 props
*/ */
isInitialized(): boolean { async init(props: QiankunProps) {
return this.requestInstance !== null; if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
} console.warn("[GSC Request] 非 qiankun 环境,无法获取 Request 实例");
return;
/** }
* 销毁管理器
if (!props.getGscRequest) {
console.warn("[GSC Request] props 中未找到 getGscRequest 函数");
return;
}
this.getGscRequestFn = props.getGscRequest;
try {
if (this.getGscRequestFn) {
this.requestInstance = await this.getGscRequestFn();
}
} catch (error) {
console.error("[GSC Request] 实例初始化失败:", error);
throw error;
}
}
/**
* 检查 Request 是否已初始化
*/ */
destroy() { isInitialized(): boolean {
this.requestInstance = null; return this.requestInstance !== null;
this.getGscRequestFn = null; }
this.initPromise = null;
}
} }
// 导出单例 // 导出单例
...@@ -98,13 +99,13 @@ export const gscRequestManager = new GscRequestManager(); ...@@ -98,13 +99,13 @@ export const gscRequestManager = new GscRequestManager();
* @returns Promise<any> 响应数据 * @returns Promise<any> 响应数据
*/ */
export async function gscPost( export async function gscPost(
url: string, url: string,
data: any, data: any,
config: any = {}, config: any = {},
): Promise<any> { ): Promise<any> {
const request = await gscRequestManager.getRequest(); const request = await gscRequestManager.getRequest();
// Request 实例有 post 方法,但类型定义可能不完整,使用类型断言 // Request 实例有 post 方法,但类型定义可能不完整,使用类型断言
return (request as any).post(url, data, config); return (request as any).post(url, data, config);
} }
/** /**
...@@ -114,9 +115,9 @@ export async function gscPost( ...@@ -114,9 +115,9 @@ export async function gscPost(
* @returns Promise<any> 响应数据 * @returns Promise<any> 响应数据
*/ */
export async function gscGet(url: string, config: any = {}): Promise<any> { export async function gscGet(url: string, config: any = {}): Promise<any> {
const request = await gscRequestManager.getRequest(); const request = await gscRequestManager.getRequest();
// Request 实例有 get 方法,但类型定义可能不完整,使用类型断言 // Request 实例有 get 方法,但类型定义可能不完整,使用类型断言
return (request as any).get(url, config); return (request as any).get(url, config);
} }
/** /**
...@@ -124,6 +125,6 @@ export async function gscGet(url: string, config: any = {}): Promise<any> { ...@@ -124,6 +125,6 @@ export async function gscGet(url: string, config: any = {}): Promise<any> {
* @returns Promise<Request> Request 实例 * @returns Promise<Request> Request 实例
*/ */
export async function getGscRequest(): Promise<Request> { export async function getGscRequest(): Promise<Request> {
return gscRequestManager.getRequest(); return gscRequestManager.getRequest();
} }
import GlOssApi from 'glsk-oss-jssdk'; import GlOssApi from "glsk-oss-jssdk";
/** /**
* 上传结果接口 * 上传结果接口
...@@ -29,71 +29,71 @@ export interface UploadOptions { ...@@ -29,71 +29,71 @@ export interface UploadOptions {
* 单例模式,统一管理文件上传 * 单例模式,统一管理文件上传
*/ */
class OssUploadManager { class OssUploadManager {
private ossApi: GlOssApi | null = null; private ossApi: GlOssApi | null = null;
/** /**
* 初始化 OSS API 实例
*/
private getOssApi(): GlOssApi {
if (!this.ossApi) {
this.ossApi = new GlOssApi();
}
return this.ossApi;
}
/**
* 上传文件 * 上传文件
* @param file 要上传的文件 * @param file 要上传的文件
* @param options 上传配置选项 * @param options 上传配置选项
* @returns Promise<UploadResult> 上传结果 * @returns Promise<UploadResult> 上传结果
*/ */
async uploadFile( async uploadFile(
file: File, file: File,
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult> { ): Promise<UploadResult> {
if (!file) { if (!file) {
throw new Error('文件不能为空'); throw new Error("文件不能为空");
} }
const ossApi = this.getOssApi(); const ossApi = this.getOssApi();
return new Promise<UploadResult>((resolve, reject) => { return new Promise<UploadResult>((resolve, reject) => {
ossApi.multipartUpload( ossApi.multipartUpload(
file, file,
(result: UploadResult) => { (result: UploadResult) => {
// 调用成功回调 // 调用成功回调
options.onSuccess?.(result); options.onSuccess?.(result);
resolve(result); resolve(result);
}, },
(error: Error) => { (error: Error) => {
// 调用失败回调 // 调用失败回调
options.onError?.(error); options.onError?.(error);
reject(error); reject(error);
}, },
); );
}); });
} }
/** /**
* 批量上传文件 * 批量上传文件
* @param files 要上传的文件数组 * @param files 要上传的文件数组
* @param options 上传配置选项 * @param options 上传配置选项
* @returns Promise<UploadResult[]> 上传结果数组 * @returns Promise<UploadResult[]> 上传结果数组
*/ */
async uploadFiles( async uploadFiles(
files: File[], files: File[],
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult[]> { ): Promise<UploadResult[]> {
if (!files || files.length === 0) { if (!files || files.length === 0) {
throw new Error('文件列表不能为空'); throw new Error("文件列表不能为空");
} }
const uploadPromises = files.map((file) => const uploadPromises = files.map((file) =>
this.uploadFile(file, options), this.uploadFile(file, options),
); );
return Promise.all(uploadPromises); return Promise.all(uploadPromises);
} }
/**
* 初始化 OSS API 实例
*/
private getOssApi(): GlOssApi {
if (!this.ossApi) {
this.ossApi = new GlOssApi();
}
return this.ossApi;
}
} }
// 导出单例实例 // 导出单例实例
...@@ -120,10 +120,10 @@ const ossUploadManager = new OssUploadManager(); ...@@ -120,10 +120,10 @@ const ossUploadManager = new OssUploadManager();
* ``` * ```
*/ */
export async function uploadFile( export async function uploadFile(
file: File, file: File,
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult> { ): Promise<UploadResult> {
return ossUploadManager.uploadFile(file, options); return ossUploadManager.uploadFile(file, options);
} }
/** /**
...@@ -146,10 +146,10 @@ export async function uploadFile( ...@@ -146,10 +146,10 @@ export async function uploadFile(
* ``` * ```
*/ */
export async function uploadFiles( export async function uploadFiles(
files: File[], files: File[],
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult[]> { ): Promise<UploadResult[]> {
return ossUploadManager.uploadFiles(files, options); return ossUploadManager.uploadFiles(files, options);
} }
/** /**
...@@ -170,28 +170,28 @@ export async function uploadFiles( ...@@ -170,28 +170,28 @@ export async function uploadFiles(
* ``` * ```
*/ */
export async function uploadFromInput( export async function uploadFromInput(
fileInput: HTMLInputElement | FileList | File[], fileInput: File[] | FileList | HTMLInputElement,
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult | UploadResult[]> { ): Promise<UploadResult | UploadResult[]> {
let files: File[] = []; let files: File[] = [];
if (fileInput instanceof HTMLInputElement) { if (fileInput instanceof HTMLInputElement) {
if (!fileInput.files || fileInput.files.length === 0) { if (!fileInput.files || fileInput.files.length === 0) {
throw new Error('请选择文件'); throw new Error("请选择文件");
} }
files = Array.from(fileInput.files); files = Array.from(fileInput.files);
} else if (fileInput instanceof FileList) { } else if (fileInput instanceof FileList) {
files = Array.from(fileInput); files = Array.from(fileInput);
} else if (Array.isArray(fileInput)) { } else if (Array.isArray(fileInput)) {
files = fileInput; files = fileInput;
} else { } else {
throw new Error('不支持的文件输入类型'); throw new TypeError("不支持的文件输入类型");
} }
if (files.length === 1) { if (files.length === 1) {
return uploadFile(files[0], options); return uploadFile(files[0], options);
} }
return uploadFiles(files, options); return uploadFiles(files, options);
} }
...@@ -254,8 +254,8 @@ const handleCurrentChange = (val) => { ...@@ -254,8 +254,8 @@ const handleCurrentChange = (val) => {
:loading="scope.row.statusLoading" :loading="scope.row.statusLoading"
style=" style="
--el-switch-on-color: #1956fe; --el-switch-on-color: #1956fe;
--el-switch-off-color: #d3d6db; --el-switch-off-color: #d3d6db;
" "
@change="handleStatusChange(scope.row)" /> @change="handleStatusChange(scope.row)" />
<span class="text-[14px] text-[#2F3133]"> <span class="text-[14px] text-[#2F3133]">
...@@ -318,32 +318,32 @@ const handleCurrentChange = (val) => { ...@@ -318,32 +318,32 @@ const handleCurrentChange = (val) => {
<style scoped> <style scoped>
/* Element Plus 表单项样式覆盖 - 使用 !important 确保优先级 */ /* Element Plus 表单项样式覆盖 - 使用 !important 确保优先级 */
.search-form :deep(.el-form-item) { .search-form :deep(.el-form-item) {
margin-right: 20px; margin-right: 20px;
margin-bottom: 0; margin-bottom: 0;
} }
/* 查询按钮样式 */ /* 查询按钮样式 */
:deep(.search-btn) { :deep(.search-btn) {
color: #1956fe !important; color: #1956fe !important;
border-color: #1956fe !important; border-color: #1956fe !important;
} }
:deep(.search-btn:hover) { :deep(.search-btn:hover) {
color: #1956fe !important; color: #1956fe !important;
background-color: rgb(25 86 254 / 10%) !important; background-color: rgb(25 86 254 / 10%) !important;
border-color: #1956fe !important; border-color: #1956fe !important;
} }
/* 自定义查询按钮样式 */ /* 自定义查询按钮样式 */
.search-btn-custom:hover { .search-btn-custom:hover {
color: #fff !important; color: #fff !important;
background-color: #3b82f6 !important; background-color: #3b82f6 !important;
border-color: #3b82f6 !important; border-color: #3b82f6 !important;
} }
/* 自定义重置按钮样式 */ /* 自定义重置按钮样式 */
.reset-btn-custom:hover { .reset-btn-custom:hover {
background-color: #f5f7fa !important; background-color: #f5f7fa !important;
} }
/* 分页组件样式 - 只对页码应用自定义样式 */ /* 分页组件样式 - 只对页码应用自定义样式 */
...@@ -354,12 +354,12 @@ const handleCurrentChange = (val) => { ...@@ -354,12 +354,12 @@ const handleCurrentChange = (val) => {
} */ } */
:deep(.el-pagination .el-pager li.is-active) { :deep(.el-pagination .el-pager li.is-active) {
color: #1956FE !important; color: #1956FE !important;
background: #d2e2ff !important; background: #d2e2ff !important;
border: 1px solid #8BAEFE !important; border: 1px solid #8BAEFE !important;
} }
.el-select-dropdown__item.selected { .el-select-dropdown__item.selected {
background-color: #1956FE!important; background-color: #1956FE!important;
} }
</style> </style>
<script setup lang="ts"> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
const router = useRouter(); const router = useRouter();
/**
* 返回首页
* 若缓存中无用户token信息,则跳转到登录页面
*/
const goHome = () => { const goHome = () => {
router.push('/'); console.log("goHome");
// 检查 localStorage 中是否存在 token
const TOKEN_KEY = "scrm_access_token";
const token = localStorage.getItem(TOKEN_KEY);
if (!token) {
// 如果没有 token,跳转到登录页面
// 登录页是基座应用的页面,直接使用绝对路径
window.location.href = "/login";
} else {
// 有 token,跳转到首页
router.push("/");
}
}; };
</script> </script>
<template> <template>
<div class="notfound-view"> <div class="notfound-view">
<div class="content-card"> <div class="content-card">
<div class="error-code">404</div> <div class="error-code">
<h1>页面未找到</h1> 404
<p>抱歉,您访问的页面不存在或已被删除</p> </div>
<button @click="goHome" class="btn-home">🏠 返回首页</button> <h1>页面未找到</h1>
<p>抱歉,您访问的页面不存在或已被删除</p>
<button class="btn-home" @click="goHome">
🏠 返回首页
</button>
</div>
</div> </div>
</div>
</template> </template>
<style scoped> <style scoped>
.notfound-view { .notfound-view {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
max-width: 600px; max-width: 600px;
min-height: 400px; min-height: 400px;
margin: 0 auto; margin: 0 auto;
} }
.content-card { .content-card {
padding: 3rem; padding: 3rem;
text-align: center; text-align: center;
background: rgb(255 255 255 / 10%); background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%); border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
} }
.error-code { .error-code {
margin-bottom: 1rem; margin-bottom: 1rem;
font-size: 6rem; font-size: 6rem;
font-weight: 700; font-weight: 700;
background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%)); background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%));
background-clip: text; background-clip: text;
-webkit-text-fill-color: transparent; -webkit-text-fill-color: transparent;
} }
.content-card h1 { .content-card h1 {
margin: 0 0 1rem; margin: 0 0 1rem;
font-size: 2rem; font-size: 2rem;
} }
.content-card p { .content-card p {
margin: 0 0 2rem; margin: 0 0 2rem;
opacity: 0.9; opacity: 0.9;
} }
.btn-home { .btn-home {
padding: 0.75rem 2rem; padding: 0.75rem 2rem;
font-size: 1rem; font-size: 1rem;
font-weight: 600; font-weight: 600;
color: white; color: white;
cursor: pointer; cursor: pointer;
background: rgb(76 175 80 / 80%); background: rgb(76 175 80 / 80%);
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-home:hover { .btn-home:hover {
background: rgb(76 175 80 / 100%); background: rgb(76 175 80 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
</style> </style>
...@@ -118,136 +118,136 @@ const deleteUser = (id: number) => { ...@@ -118,136 +118,136 @@ const deleteUser = (id: number) => {
<style scoped> <style scoped>
.user-view { .user-view {
max-width: 1200px; max-width: 1200px;
margin: 0 auto; margin: 0 auto;
} }
.content-card { .content-card {
padding: 2.5rem; padding: 2.5rem;
background: rgb(255 255 255 / 10%); background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%); border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem; border-radius: 1rem;
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
} }
.content-card h1 { .content-card h1 {
margin: 0 0 1.5rem; margin: 0 0 1.5rem;
font-size: 2rem; font-size: 2rem;
} }
.toolbar { .toolbar {
margin-bottom: 1.5rem; margin-bottom: 1.5rem;
} }
.btn-add { .btn-add {
padding: 0.75rem 1.5rem; padding: 0.75rem 1.5rem;
font-weight: 600; font-weight: 600;
color: white; color: white;
cursor: pointer; cursor: pointer;
background: rgb(76 175 80 / 80%); background: rgb(76 175 80 / 80%);
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-add:hover { .btn-add:hover {
background: rgb(76 175 80 / 100%); background: rgb(76 175 80 / 100%);
transform: translateY(-2px); transform: translateY(-2px);
} }
.table-container { .table-container {
overflow-x: auto; overflow-x: auto;
} }
.user-table { .user-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
} }
.user-table thead { .user-table thead {
background: rgb(255 255 255 / 10%); background: rgb(255 255 255 / 10%);
} }
.user-table th, .user-table th,
.user-table td { .user-table td {
padding: 1rem; padding: 1rem;
text-align: left; text-align: left;
border-bottom: 1px solid rgb(255 255 255 / 10%); border-bottom: 1px solid rgb(255 255 255 / 10%);
} }
.user-table th { .user-table th {
font-weight: 600; font-weight: 600;
color: rgb(255 255 255 / 95%); color: rgb(255 255 255 / 95%);
} }
.user-table tbody tr { .user-table tbody tr {
transition: background 0.3s ease; transition: background 0.3s ease;
} }
.user-table tbody tr:hover { .user-table tbody tr:hover {
background: rgb(255 255 255 / 5%); background: rgb(255 255 255 / 5%);
} }
.badge { .badge {
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 600; font-weight: 600;
border-radius: 1rem; border-radius: 1rem;
} }
.badge-admin { .badge-admin {
background: rgb(244 67 54 / 80%); background: rgb(244 67 54 / 80%);
} }
.badge-user { .badge-user {
background: rgb(33 150 243 / 80%); background: rgb(33 150 243 / 80%);
} }
.badge-guest { .badge-guest {
background: rgb(158 158 158 / 80%); background: rgb(158 158 158 / 80%);
} }
.status { .status {
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 600; font-weight: 600;
border-radius: 1rem; border-radius: 1rem;
} }
.status-active { .status-active {
background: rgb(76 175 80 / 80%); background: rgb(76 175 80 / 80%);
} }
.status-inactive { .status-inactive {
background: rgb(158 158 158 / 80%); background: rgb(158 158 158 / 80%);
} }
.btn-edit, .btn-edit,
.btn-delete { .btn-delete {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
margin-right: 0.5rem; margin-right: 0.5rem;
font-weight: 600; font-weight: 600;
cursor: pointer; cursor: pointer;
border: none; border: none;
border-radius: 0.5rem; border-radius: 0.5rem;
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.btn-edit { .btn-edit {
color: white; color: white;
background: rgb(33 150 243 / 80%); background: rgb(33 150 243 / 80%);
} }
.btn-edit:hover { .btn-edit:hover {
background: rgb(33 150 243 / 100%); background: rgb(33 150 243 / 100%);
} }
.btn-delete { .btn-delete {
color: white; color: white;
background: rgb(244 67 54 / 80%); background: rgb(244 67 54 / 80%);
} }
.btn-delete:hover { .btn-delete:hover {
background: rgb(244 67 54 / 100%); background: rgb(244 67 54 / 100%);
} }
</style> </style>
export { default } from '@venus/tailwind-config'; export { default } from "@venus/tailwind-config";
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2020", "target": "ES2020",
"jsx": "preserve", "jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"], "lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true, "useDefineForClassFields": true,
/* Path Alias */ /* Path Alias */
"baseUrl": ".", "baseUrl": ".",
"module": "ESNext", "module": "ESNext",
/* Bundler mode */ /* Bundler mode */
"moduleResolution": "bundler", "moduleResolution": "bundler",
"paths": { "paths": {
"@/*": ["src/*"] "@/*": ["src/*"]
}, },
"resolveJsonModule": true, "resolveJsonModule": true,
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"allowJs": true, "allowJs": true,
/* Linting */ /* Linting */
"strict": true, "strict": true,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noEmit": true, "noEmit": true,
"isolatedModules": true, "isolatedModules": true,
"skipLibCheck": true "skipLibCheck": true
}, },
"references": [{ "path": "./tsconfig.node.json" }], "references": [{ "path": "./tsconfig.node.json" }],
"include": [ "include": ["env.d.ts", "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/*.js"]
"env.d.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.js"
]
} }
{ {
"compilerOptions": { "compilerOptions": {
"composite": true, "composite": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "bundler", "moduleResolution": "bundler",
"paths": { "paths": {
"@venus/tools/*": ["../../../../packages/tools/src/*"] "@venus/tools/*": ["../../../../packages/tools/src/*"]
}, },
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"skipLibCheck": true "skipLibCheck": true
}, },
"include": ["vite.config.ts", "vite-plugins/**/*.ts"] "include": ["vite.config.ts", "vite-plugins/**/*.ts"],
"exclude": ["env.d.ts"]
} }
...@@ -73,16 +73,16 @@ pnpm preview ...@@ -73,16 +73,16 @@ pnpm preview
```typescript ```typescript
export const microApps: MicroAppConfig[] = [ export const microApps: MicroAppConfig[] = [
{ {
name: 'subapp-vue', // 微应用名称 name: "subapp-vue", // 微应用名称
entry: '//localhost:8081', // 微应用入口 entry: "//localhost:8081", // 微应用入口
container: '#subapp-container', // 微应用挂载点 container: "#subapp-container", // 微应用挂载点
activeRule: '/subapp-vue', // 激活路由 activeRule: "/subapp-vue", // 激活路由
props: { props: {
routerBase: '/subapp-vue', // 路由基础路径 routerBase: "/subapp-vue", // 路由基础路径
}, },
}, },
// 添加更多微应用... // 添加更多微应用...
]; ];
``` ```
...@@ -104,10 +104,10 @@ export const microApps: MicroAppConfig[] = [ ...@@ -104,10 +104,10 @@ export const microApps: MicroAppConfig[] = [
- **顶部导航栏**: 包含 Logo、主菜单和用户信息 - **顶部导航栏**: 包含 Logo、主菜单和用户信息
- **侧边栏**: 可折叠的侧边导航菜单 - **侧边栏**: 可折叠的侧边导航菜单
- **内容区域**: - **内容区域**:
- 面包屑导航 - 面包屑导航
- 页面内容容器 - 页面内容容器
- 微应用挂载容器(`#subapp-container`) - 微应用挂载容器(`#subapp-container`)
- **底部**: 版权信息 - **底部**: 版权信息
## qiankun 配置 ## qiankun 配置
...@@ -115,24 +115,24 @@ export const microApps: MicroAppConfig[] = [ ...@@ -115,24 +115,24 @@ export const microApps: MicroAppConfig[] = [
主应用在 `main.ts` 中初始化 qiankun: 主应用在 `main.ts` 中初始化 qiankun:
```typescript ```typescript
import { registerMicroApps, start } from 'qiankun'; import { registerMicroApps, start } from "qiankun";
// 注册微应用 // 注册微应用
registerMicroApps(microApps, { registerMicroApps(microApps, {
beforeLoad: (app) => console.log('before load', app.name), beforeLoad: (app) => console.log("before load", app.name),
beforeMount: (app) => console.log('before mount', app.name), beforeMount: (app) => console.log("before mount", app.name),
afterMount: (app) => console.log('after mount', app.name), afterMount: (app) => console.log("after mount", app.name),
beforeUnmount: (app) => console.log('before unmount', app.name), beforeUnmount: (app) => console.log("before unmount", app.name),
afterUnmount: (app) => console.log('after unmount', app.name), afterUnmount: (app) => console.log("after unmount", app.name),
}); });
// 启动 qiankun // 启动 qiankun
start({ start({
prefetch: true, // 预加载 prefetch: true, // 预加载
sandbox: { sandbox: {
strictStyleIsolation: false, strictStyleIsolation: false,
experimentalStyleIsolation: true, experimentalStyleIsolation: true,
}, },
}); });
``` ```
...@@ -151,17 +151,17 @@ start({ ...@@ -151,17 +151,17 @@ start({
let instance: any = null; let instance: any = null;
export async function bootstrap() { export async function bootstrap() {
console.log('vue app bootstraped'); console.log("vue app bootstraped");
} }
export async function mount(props: any) { export async function mount(props: any) {
instance = createApp(App); instance = createApp(App);
instance.mount(props.container ? props.container.querySelector('#app') : '#app'); instance.mount(props.container ? props.container.querySelector("#app") : "#app");
} }
export async function unmount() { export async function unmount() {
instance.unmount(); instance.unmount();
instance = null; instance = null;
} }
``` ```
...@@ -169,20 +169,20 @@ export async function unmount() { ...@@ -169,20 +169,20 @@ export async function unmount() {
```typescript ```typescript
// vite.config.ts // vite.config.ts
import qiankun from 'vite-plugin-qiankun'; import qiankun from "vite-plugin-qiankun";
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
vue(), vue(),
qiankun('subapp-vue', { qiankun("subapp-vue", {
useDevMode: true useDevMode: true,
}) }),
], ],
server: { server: {
port: 8081, port: 8081,
cors: true, cors: true,
origin: 'http://localhost:8081' origin: "http://localhost:8081",
} },
}); });
``` ```
...@@ -223,4 +223,3 @@ export default defineConfig({ ...@@ -223,4 +223,3 @@ export default defineConfig({
## License ## License
MIT MIT
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
## 🚀 功能特性 ## 🚀 功能特性
### 1. 登录页面 ### 1. 登录页面
- ✅ 现代化 UI 设计,支持响应式布局 - ✅ 现代化 UI 设计,支持响应式布局
- ✅ 用户名密码登录 - ✅ 用户名密码登录
- ✅ 验证码功能(可选) - ✅ 验证码功能(可选)
...@@ -16,11 +17,13 @@ ...@@ -16,11 +17,13 @@
- ✅ 加载状态显示 - ✅ 加载状态显示
### 2. 状态管理(Pinia) ### 2. 状态管理(Pinia)
- ✅ 用户状态管理(`useUserStore`) - ✅ 用户状态管理(`useUserStore`)
- ✅ 权限管理(`usePermissionStore`) - ✅ 权限管理(`usePermissionStore`)
- ✅ 应用全局状态管理(`useAppStore`) - ✅ 应用全局状态管理(`useAppStore`)
### 3. 认证与授权 ### 3. 认证与授权
- ✅ Token 存储和管理 - ✅ Token 存储和管理
- ✅ 自动刷新用户信息 - ✅ 自动刷新用户信息
- ✅ 路由守卫 - ✅ 路由守卫
...@@ -28,6 +31,7 @@ ...@@ -28,6 +31,7 @@
- ✅ 角色检查 - ✅ 角色检查
### 4. API 封装 ### 4. API 封装
- ✅ Axios 请求拦截器 - ✅ Axios 请求拦截器
- ✅ 响应拦截器 - ✅ 响应拦截器
- ✅ 自动添加 Token - ✅ 自动添加 Token
...@@ -106,19 +110,19 @@ graph TD ...@@ -106,19 +110,19 @@ graph TD
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
const handleLogin = async () => { const handleLogin = async () => {
const result = await userStore.login({ const result = await userStore.login({
username: 'admin', username: "admin",
password: '123456', password: "123456",
}); });
if (result.success) { if (result.success) {
console.log('登录成功'); console.log("登录成功");
} }
}; };
</script> </script>
``` ```
...@@ -127,7 +131,7 @@ const handleLogin = async () => { ...@@ -127,7 +131,7 @@ const handleLogin = async () => {
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
</script> </script>
``` ```
...@@ -136,18 +140,18 @@ const userStore = useUserStore(); ...@@ -136,18 +140,18 @@ const userStore = useUserStore();
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
// 检查权限 // 检查权限
if (userStore.hasPermission('user:create')) { if (userStore.hasPermission("user:create")) {
console.log('有创建用户权限'); console.log("有创建用户权限");
} }
// 检查角色 // 检查角色
if (userStore.hasRole('admin')) { if (userStore.hasRole("admin")) {
console.log('是管理员'); console.log("是管理员");
} }
</script> </script>
``` ```
...@@ -156,15 +160,15 @@ if (userStore.hasRole('admin')) { ...@@ -156,15 +160,15 @@ if (userStore.hasRole('admin')) {
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
const handleLogout = async () => { const handleLogout = async () => {
await userStore.logout(); await userStore.logout();
router.push('/login'); router.push("/login");
}; };
</script> </script>
``` ```
...@@ -202,7 +206,7 @@ VITE_API_BASE_URL=http://localhost:3000/api ...@@ -202,7 +206,7 @@ VITE_API_BASE_URL=http://localhost:3000/api
在 `router/index.ts` 中配置不需要登录的路由: 在 `router/index.ts` 中配置不需要登录的路由:
```typescript ```typescript
const whiteList = ['/login', '/register', '/forgot-password']; const whiteList = ["/login", "/register", "/forgot-password"];
``` ```
### 3. Token 存储 Key ### 3. Token 存储 Key
...@@ -210,8 +214,8 @@ const whiteList = ['/login', '/register', '/forgot-password']; ...@@ -210,8 +214,8 @@ const whiteList = ['/login', '/register', '/forgot-password'];
在 `utils/auth.ts` 中配置: 在 `utils/auth.ts` 中配置:
```typescript ```typescript
const TOKEN_KEY = 'scrm_access_token'; const TOKEN_KEY = "scrm_access_token";
const REFRESH_TOKEN_KEY = 'scrm_refresh_token'; const REFRESH_TOKEN_KEY = "scrm_refresh_token";
``` ```
## 🌐 API 接口规范 ## 🌐 API 接口规范
...@@ -219,6 +223,7 @@ const REFRESH_TOKEN_KEY = 'scrm_refresh_token'; ...@@ -219,6 +223,7 @@ const REFRESH_TOKEN_KEY = 'scrm_refresh_token';
### 1. 登录接口 ### 1. 登录接口
**请求:** **请求:**
```http ```http
POST /auth/login POST /auth/login
Content-Type: application/json Content-Type: application/json
...@@ -231,62 +236,67 @@ Content-Type: application/json ...@@ -231,62 +236,67 @@ Content-Type: application/json
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
"message": "登录成功", "message": "登录成功",
"data": { "data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "...", "refreshToken": "...",
"userInfo": { "userInfo": {
"id": "1", "id": "1",
"username": "admin", "username": "admin",
"name": "管理员", "name": "管理员",
"avatar": "https://...", "avatar": "https://...",
"roles": ["admin"], "roles": ["admin"],
"permissions": ["*:*:*"] "permissions": ["*:*:*"]
} }
} }
} }
``` ```
### 2. 获取用户信息接口 ### 2. 获取用户信息接口
**请求:** **请求:**
```http ```http
GET /user/info GET /user/info
Authorization: Bearer {token} Authorization: Bearer {token}
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
"message": "success", "message": "success",
"data": { "data": {
"id": "1", "id": "1",
"username": "admin", "username": "admin",
"name": "管理员", "name": "管理员",
"avatar": "https://...", "avatar": "https://...",
"roles": ["admin"], "roles": ["admin"],
"permissions": ["*:*:*"] "permissions": ["*:*:*"]
} }
} }
``` ```
### 3. 登出接口 ### 3. 登出接口
**请求:** **请求:**
```http ```http
POST /auth/logout POST /auth/logout
Authorization: Bearer {token} Authorization: Bearer {token}
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
"message": "登出成功" "message": "登出成功"
} }
``` ```
...@@ -296,32 +306,32 @@ Authorization: Bearer {token} ...@@ -296,32 +306,32 @@ Authorization: Bearer {token}
```css ```css
.login-container { .login-container {
/* 背景渐变色 */ /* 背景渐变色 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
} }
.login-button { .login-button {
/* 按钮渐变色 */ /* 按钮渐变色 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
} }
``` ```
## 🔒 安全建议 ## 🔒 安全建议
1. **密码安全** 1. **密码安全**
- 不在前端存储明文密码 - 不在前端存储明文密码
- 使用 HTTPS 传输 - 使用 HTTPS 传输
- 密码输入框使用 autocomplete="current-password" - 密码输入框使用 autocomplete="current-password"
2. **Token 安全** 2. **Token 安全**
- Token 存储在 localStorage(建议生产环境使用 httpOnly cookie) - Token 存储在 localStorage(建议生产环境使用 httpOnly cookie)
- 设置合理的过期时间 - 设置合理的过期时间
- 实现 Token 刷新机制 - 实现 Token 刷新机制
3. **权限控制** 3. **权限控制**
- 前端权限检查 + 后端权限验证 - 前端权限检查 + 后端权限验证
- 敏感操作二次确认 - 敏感操作二次确认
- 最小权限原则 - 最小权限原则
## 📝 测试 ## 📝 测试
...@@ -332,22 +342,22 @@ Authorization: Bearer {token} ...@@ -332,22 +342,22 @@ Authorization: Bearer {token}
```typescript ```typescript
// 修改 api/user.ts 添加模拟数据 // 修改 api/user.ts 添加模拟数据
export const login = (data: LoginParams) => { export const login = (data: LoginParams) => {
// 模拟登录 // 模拟登录
return Promise.resolve({ return Promise.resolve({
code: 200, code: 200,
message: '登录成功', message: "登录成功",
data: { data: {
token: 'mock_token_' + Date.now(), token: "mock_token_" + Date.now(),
userInfo: { userInfo: {
id: '1', id: "1",
username: data.username, username: data.username,
name: '测试用户', name: "测试用户",
avatar: '👤', avatar: "👤",
roles: ['admin'], roles: ["admin"],
permissions: ['*:*:*'], permissions: ["*:*:*"],
}, },
}, },
}); });
}; };
``` ```
...@@ -361,7 +371,7 @@ export const login = (data: LoginParams) => { ...@@ -361,7 +371,7 @@ export const login = (data: LoginParams) => {
// main.ts // main.ts
const token = getToken(); const token = getToken();
if (token) { if (token) {
userStore.setTokenValue(token); userStore.setTokenValue(token);
} }
``` ```
...@@ -370,8 +380,8 @@ if (token) { ...@@ -370,8 +380,8 @@ if (token) {
检查路由守卫中是否正确处理了白名单和登录页: 检查路由守卫中是否正确处理了白名单和登录页:
```typescript ```typescript
if (to.path === '/login') { if (to.path === "/login") {
next(); // 必须放行登录页 next(); // 必须放行登录页
} }
``` ```
...@@ -380,7 +390,7 @@ if (to.path === '/login') { ...@@ -380,7 +390,7 @@ if (to.path === '/login') {
检查请求拦截器是否正确添加 Token: 检查请求拦截器是否正确添加 Token:
```typescript ```typescript
config.headers['Authorization'] = `Bearer ${token}`; config.headers["Authorization"] = `Bearer ${token}`;
``` ```
## 📚 相关文档 ## 📚 相关文档
...@@ -392,4 +402,3 @@ config.headers['Authorization'] = `Bearer ${token}`; ...@@ -392,4 +402,3 @@ config.headers['Authorization'] = `Bearer ${token}`;
## 🙋 支持 ## 🙋 支持
如有问题,请联系开发团队或提交 Issue。 如有问题,请联系开发团队或提交 Issue。
/// <reference types="vite/client" /> // / <reference types="vite/client" />
declare module '*.vue' { declare module "*.vue" {
import type { DefineComponent } from 'vue'; import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<object, object, any>;
export default component; export default component;
} }
...@@ -16,7 +16,7 @@ interface ImportMeta { ...@@ -16,7 +16,7 @@ interface ImportMeta {
readonly env: ImportMetaEnv; readonly env: ImportMetaEnv;
} }
// declare module 手动提供模块类型定义,避免异常 // declare module 手动提供模块类型定义,避免异常
declare module 'glsk-common' { declare module "glsk-common" {
export interface HttpConfig { export interface HttpConfig {
response?: any; response?: any;
request?: any; request?: any;
...@@ -24,14 +24,14 @@ declare module 'glsk-common' { ...@@ -24,14 +24,14 @@ declare module 'glsk-common' {
secret?: any; secret?: any;
alert?: (message: string) => void; alert?: (message: string) => void;
} }
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class Http { export class Http {
[key: string]: any; [key: string]: any;
constructor(config: HttpConfig); constructor(config: HttpConfig);
} }
} }
declare module 'glsk-toolkit' { declare module "glsk-toolkit" {
export class Request { export class Request {
[key: string]: any; [key: string]: any;
constructor(config: any); constructor(config: any);
......
<!DOCTYPE html> <!doctype html>
<html lang="zh-CN" style="--el-color-primary: #185EFE; "> <html lang="zh-CN" style="--el-color-primary: #185efe">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>汽车销售超级孪生智能体</title> <title>汽车销售超级孪生智能体</title>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>
{ {
"name": "@venus/venus-agentic-base", "name": "@venus/venus-agentic-base",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --host", "dev": "vite --host",
"build": "vue-tsc && vite build", "build": "vue-tsc && vite build",
"postbuild": "node ../../../../scripts/copy-dist-to-root.mjs", "postbuild": "node ../../../../scripts/copy-dist-to-root.mjs",
"preview": "vite preview", "preview": "vite preview",
"type-check": "vue-tsc --noEmit" "type-check": "vue-tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "catalog:", "@element-plus/icons-vue": "catalog:",
"@venus/common-ui-vue": "workspace:*", "@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"axios": "catalog:", "axios": "catalog:",
"element-plus": "catalog:", "element-plus": "catalog:",
"glsk-toolkit": "catalog:", "glsk-toolkit": "catalog:",
"jsencrypt": "catalog:", "jsencrypt": "catalog:",
"pinia": "catalog:", "pinia": "catalog:",
"qiankun": "catalog:", "qiankun": "catalog:",
"vue": "catalog:", "vue": "catalog:",
"vue-router": "catalog:" "vue-router": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "catalog:", "@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:", "@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:", "@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:", "typescript": "catalog:",
"unplugin-auto-import": "catalog:", "unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:", "unplugin-vue-components": "catalog:",
"vite": "catalog:", "vite": "catalog:",
"vite-plugin-qiankun": "catalog:", "vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:" "vue-tsc": "catalog:"
} }
} }
export * from './route'; export * from "./route";
/** /**
* API 统一导出 * API 统一导出
*/ */
export * from './user'; export * from "./user";
...@@ -2,152 +2,152 @@ ...@@ -2,152 +2,152 @@
* 模拟 API(用于开发测试,后端接口完成后可删除此文件) * 模拟 API(用于开发测试,后端接口完成后可删除此文件)
*/ */
import type { ApiResponse } from '@/types/api'; import type { ApiResponse } from "@/types/api";
import type { LoginParams, LoginResponse, UserInfo } from '@/types/user'; import type { LoginParams, LoginResponse, UserInfo } from "@/types/user";
/** /**
* 模拟延迟 * 模拟延迟
*/ */
const mockDelay = (ms: number = 500) => { const mockDelay = (ms: number = 500) => {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
}; };
/** /**
* 模拟用户数据 * 模拟用户数据
*/ */
const mockUsers = [ const mockUsers = [
{ {
username: 'admin', username: "admin",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '1', id: "1",
username: 'admin', username: "admin",
name: '管理员', name: "管理员",
avatar: '👤', avatar: "👤",
email: 'admin@scrm.com', email: "admin@scrm.com",
phone: '13800138000', phone: "13800138000",
roles: ['admin', 'user'], roles: [ "admin", "user" ],
permissions: ['*:*:*'], permissions: [ "*:*:*" ],
department: '技术部', department: "技术部",
position: '系统管理员', position: "系统管理员",
status: 1, status: 1,
}, },
}, },
{ {
username: 'user', username: "user",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '2', id: "2",
username: 'user', username: "user",
name: '普通用户', name: "普通用户",
avatar: '👨', avatar: "👨",
email: 'user@scrm.com', email: "user@scrm.com",
phone: '13800138001', phone: "13800138001",
roles: ['user'], roles: [ "user" ],
permissions: ['user:read', 'user:write'], permissions: [ "user:read", "user:write" ],
department: '销售部', department: "销售部",
position: '销售专员', position: "销售专员",
status: 1, status: 1,
}, },
}, },
{ {
username: 'guest', username: "guest",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '3', id: "3",
username: 'guest', username: "guest",
name: '访客', name: "访客",
avatar: '🧑', avatar: "🧑",
email: 'guest@scrm.com', email: "guest@scrm.com",
phone: '13800138002', phone: "13800138002",
roles: ['guest'], roles: [ "guest" ],
permissions: ['user:read'], permissions: [ "user:read" ],
department: '访客', department: "访客",
position: '访客', position: "访客",
status: 1, status: 1,
}, },
}, },
]; ];
/** /**
* 模拟登录 * 模拟登录
*/ */
export const mockLogin = async ( export const mockLogin = async (
data: LoginParams, data: LoginParams,
): Promise<ApiResponse<LoginResponse>> => { ): Promise<ApiResponse<LoginResponse>> => {
await mockDelay(800); await mockDelay(800);
const user = mockUsers.find((u) => u.username === data.username); const user = mockUsers.find((u) => u.username === data.username);
if (!user) { if (!user) {
return { return {
code: 400, code: 400,
message: '用户不存在', message: "用户不存在",
data: null as any, data: null as any,
}; };
} }
if (user.password !== data.password) { if (user.password !== data.password) {
return { return {
code: 400, code: 400,
message: '密码错误', message: "密码错误",
data: null as any, data: null as any,
}; };
} }
// 生成模拟 token // 生成模拟 token
const token = `mock_token_${user.username}_${Date.now()}`; const token = `mock_token_${user.username}_${Date.now()}`;
const refreshToken = `mock_refresh_token_${user.username}_${Date.now()}`; const refreshToken = `mock_refresh_token_${user.username}_${Date.now()}`;
return { return {
code: 200, code: 200,
message: '登录成功', message: "登录成功",
data: { data: {
token, token,
refreshToken, refreshToken,
userInfo: user.userInfo, userInfo: user.userInfo,
}, },
}; };
}; };
/** /**
* 模拟登出 * 模拟登出
*/ */
export const mockLogout = async (): Promise<ApiResponse<void>> => { export const mockLogout = async (): Promise<ApiResponse<void>> => {
await mockDelay(300); await mockDelay(300);
return { return {
code: 200, code: 200,
message: '登出成功', message: "登出成功",
data: undefined as any, data: undefined as any,
}; };
}; };
/** /**
* 模拟获取用户信息 * 模拟获取用户信息
*/ */
export const mockGetUserInfo = async ( export const mockGetUserInfo = async (
token: string, token: string,
): Promise<ApiResponse<UserInfo>> => { ): Promise<ApiResponse<UserInfo>> => {
await mockDelay(500); await mockDelay(500);
// 从 token 中解析用户名 // 从 token 中解析用户名
const username = token.split('_')[2]; const username = token.split("_")[2];
const user = mockUsers.find((u) => u.username === username); const user = mockUsers.find((u) => u.username === username);
if (!user) { if (!user) {
return { return {
code: 401, code: 401,
message: 'Token 无效', message: "Token 无效",
data: null as any, data: null as any,
}; };
} }
return { return {
code: 200, code: 200,
message: 'success', message: "success",
data: user.userInfo, data: user.userInfo,
}; };
}; };
/** /**
......
/** /**
* 路由和菜单相关 API * 路由和菜单相关 API
*/ */
import type { MenuItem, TopMenuItem } from '@/types/menu'; import type { MenuItem, TopMenuItem } from "@/types/menu";
import type { RouteRecordRaw } from 'vue-router';
import type { RouteRecordRaw } from "vue-router";
/** /**
* 路由配置接口(从 API 返回的数据结构) * 路由配置接口(从 API 返回的数据结构)
*/ */
...@@ -37,15 +38,15 @@ export interface MenuConfig { ...@@ -37,15 +38,15 @@ export interface MenuConfig {
id: string; id: string;
path: string; path: string;
sidebarMenus: Array<{ sidebarMenus: Array<{
children?: MenuConfig['topMenus'][0]['sidebarMenus']; children?: MenuConfig["topMenus"][0]["sidebarMenus"];
hidden?: boolean;
icon?: string; icon?: string;
id: string; id: string;
level?: number; level?: number;
meta?: MenuItem['meta']; meta?: MenuItem["meta"];
parentId?: string; parentId?: string;
path: string; path: string;
title: string; title: string;
hidden?: boolean;
}>; }>;
title: string; title: string;
}>; }>;
...@@ -57,29 +58,29 @@ export interface MenuConfig { ...@@ -57,29 +58,29 @@ export interface MenuConfig {
* 将 API 返回的路由配置转换为 Vue Router 路由格式 * 将 API 返回的路由配置转换为 Vue Router 路由格式
*/ */
export function transformRouteConfig(config: RouteConfig): RouteRecordRaw { export function transformRouteConfig(config: RouteConfig): RouteRecordRaw {
// 微应用路由使用 MicroApp 组件 // 微应用路由使用 MicroApp 组件
const component = config.isMicroApp const component = config.isMicroApp
? () => import('@/views/MicroApp.vue') ? () => import("@/views/MicroApp.vue")
: // 非微应用路由需要根据实际情况设置组件 : // 非微应用路由需要根据实际情况设置组件
// 如果 API 返回了组件路径,可以在这里动态导入 // 如果 API 返回了组件路径,可以在这里动态导入
// 示例:() => import(`@/views/${config.component}.vue`); // 示例:() => import(`@/views/${config.component}.vue`);
// 目前暂时使用 MicroApp 作为默认组件,实际使用时需要根据 API 返回的数据设置 // 目前暂时使用 MicroApp 作为默认组件,实际使用时需要根据 API 返回的数据设置
() => import('@/views/MicroApp.vue'); () => import("@/views/MicroApp.vue");
return { return {
path: config.path, path: config.path,
name: config.name, name: config.name,
component, component,
meta: { meta: {
title: config.title, title: config.title,
level: config.level, level: config.level,
isMicroApp: config.isMicroApp, isMicroApp: config.isMicroApp,
requiresAuth: config.requiresAuth !== false, requiresAuth: config.requiresAuth !== false,
authority: config.authority, // 权限码(推荐使用) authority: config.authority, // 权限码(推荐使用)
permissions: config.permissions, // 兼容旧版本 permissions: config.permissions, // 兼容旧版本
roles: config.roles, roles: config.roles,
}, },
}; };
} }
/** /**
...@@ -89,34 +90,35 @@ export function transformMenuConfig(config: MenuConfig): { ...@@ -89,34 +90,35 @@ export function transformMenuConfig(config: MenuConfig): {
routes: RouteRecordRaw[]; routes: RouteRecordRaw[];
topMenus: TopMenuItem[]; topMenus: TopMenuItem[];
} { } {
const topMenus: TopMenuItem[] = config.topMenus.map((topMenu) => ({ const topMenus: TopMenuItem[] = config.topMenus.map((topMenu) => ({
id: topMenu.id, id: topMenu.id,
title: topMenu.title, title: topMenu.title,
path: topMenu.path, path: topMenu.path,
icon: topMenu.icon, icon: topMenu.icon,
sidebarMenus: transformSidebarMenus(topMenu.sidebarMenus), sidebarMenus: transformSidebarMenus(topMenu.sidebarMenus),
})); }));
const routes: RouteRecordRaw[] = config.routes.map(transformRouteConfig); // eslint-disable-next-line unicorn/no-array-callback-reference
const routes: RouteRecordRaw[] = config.routes.map(transformRouteConfig);
return { topMenus, routes }; return { topMenus, routes };
} }
/** /**
* 递归转换侧边栏菜单 * 递归转换侧边栏菜单
*/ */
function transformSidebarMenus( function transformSidebarMenus(
menus: MenuConfig['topMenus'][0]['sidebarMenus'], menus: MenuConfig["topMenus"][0]["sidebarMenus"],
): MenuItem[] { ): MenuItem[] {
return menus.map((menu) => ({ return menus.map((menu) => ({
id: menu.id, id: menu.id,
title: menu.title, title: menu.title,
path: menu.path, path: menu.path,
icon: menu.icon, icon: menu.icon,
level: menu.level, level: menu.level,
parentId: menu.parentId, parentId: menu.parentId,
children: menu.children ? transformSidebarMenus(menu.children) : undefined, children: menu.children ? transformSidebarMenus(menu.children) : undefined,
meta: menu.meta, meta: menu.meta,
hidden: menu.hidden, hidden: menu.hidden,
})); }));
} }
...@@ -2,22 +2,23 @@ ...@@ -2,22 +2,23 @@
* 用户相关 API * 用户相关 API
*/ */
import type { ApiResponse } from '@/types/api'; import type { ApiResponse } from "@/types/api";
import type { import type {
ChangePasswordParams, ChangePasswordParams,
LoginParams, LoginParams,
UpdateUserInfoParams, UpdateUserInfoParams,
UserInfo, UserInfo,
} from '@/types/user'; } from "@/types/user";
import { post } from '@/utils/request'; import gscPost from "@/config/gscrequest";
import gscPost from '@/config/gscrequest'; import { post } from "@/utils/request";
import { mockLogout } from "./mock";
// 数据看板指标统计 // 数据看板指标统计
export function getdataBoard(data: any) { export function getdataBoard(data: any) {
return gscPost('/dataBoard/indexs', data); return gscPost("/dataBoard/indexs", data);
} }
import { mockLogout } from './mock';
const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false
...@@ -25,28 +26,28 @@ const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 fa ...@@ -25,28 +26,28 @@ const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 fa
* 用户登录 * 用户登录
*/ */
export const login = (data: LoginParams) => { export const login = (data: LoginParams) => {
return gscPost('/login',data,{ returnAll:true }); return gscPost("/login", data, { returnAll:true });
}; };
/** /**
* 公钥 * 公钥
*/ */
export const getPublicKey = (data: any) => { export const getPublicKey = (data: any) => {
return gscPost('/login/publicKey',data,{ returnAll:true }); return gscPost("/login/publicKey", data, { returnAll:true });
}; };
/** /**
* 获取当前用户信息 * 获取当前用户信息
*/ */
export const getUserInfo = () => { export const getUserInfo = () => {
return gscPost('/login/currLoginUser', {}, { returnAll: true }); return gscPost("/login/currLoginUser", {}, { returnAll: true });
}; };
/** /**
* 用户登出 * 用户登出
*/ */
export const logout = () => { export const logout = () => {
if (USE_MOCK_API) { if (USE_MOCK_API) {
return mockLogout(); return mockLogout();
} }
return post<ApiResponse<void>>('/auth/logout'); return post<ApiResponse<void>>("/auth/logout");
}; };
...@@ -54,31 +55,31 @@ export const logout = () => { ...@@ -54,31 +55,31 @@ export const logout = () => {
* 刷新 Token * 刷新 Token
*/ */
export const refreshToken = (refreshToken: string) => { export const refreshToken = (refreshToken: string) => {
return post<ApiResponse<{ refreshToken: string; token: string }>>( return post<ApiResponse<{ refreshToken: string; token: string }>>(
'/auth/refresh', "/auth/refresh",
{ {
refreshToken, refreshToken,
}, },
); );
}; };
/** /**
* 修改密码 * 修改密码
*/ */
export const changePassword = (data: ChangePasswordParams) => { export const changePassword = (data: ChangePasswordParams) => {
return post<ApiResponse<void>>('/user/change-password', data); return post<ApiResponse<void>>("/user/change-password", data);
}; };
/** /**
* 更新用户信息 * 更新用户信息
*/ */
export const updateUserInfo = (data: UpdateUserInfoParams) => { export const updateUserInfo = (data: UpdateUserInfoParams) => {
return post<ApiResponse<UserInfo>>('/user/update', data); return post<ApiResponse<UserInfo>>("/user/update", data);
}; };
/** /**
* 获取验证码 * 获取验证码
*/ */
export const getCaptcha = (data: any) => { export const getCaptcha = (data: any) => {
return gscPost('/login/captcha',data); return gscPost("/login/captcha", data);
}; };
...@@ -19,58 +19,58 @@ const appStore = useAppStore(); ...@@ -19,58 +19,58 @@ const appStore = useAppStore();
<style scoped> <style scoped>
.global-loading { .global-loading {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
z-index: 9999; z-index: 9999;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 100%; width: 100%;
height: 100%; height: 100%;
background: rgb(255 255 255 / 80%); background: rgb(255 255 255 / 80%);
backdrop-filter: blur(4px); backdrop-filter: blur(4px);
} }
.loading-content { .loading-content {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px; gap: 16px;
align-items: center; align-items: center;
} }
.loading-spinner { .loading-spinner {
width: 48px; width: 48px;
height: 48px; height: 48px;
border: 4px solid #f3f3f3; border: 4px solid #f3f3f3;
border-top: 4px solid #1890ff; border-top: 4px solid #1890ff;
border-radius: 50%; border-radius: 50%;
animation: spin 1s linear infinite; animation: spin 1s linear infinite;
} }
.loading-text { .loading-text {
margin: 0; margin: 0;
font-size: 14px; font-size: 14px;
color: #666; color: #666;
} }
@keyframes spin { @keyframes spin {
0% { 0% {
transform: rotate(0deg); transform: rotate(0deg);
} }
100% { 100% {
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
.fade-enter-active, .fade-enter-active,
.fade-leave-active { .fade-leave-active {
transition: opacity 0.3s ease; transition: opacity 0.3s ease;
} }
.fade-enter-from, .fade-enter-from,
.fade-leave-to { .fade-leave-to {
opacity: 0; opacity: 0;
} }
</style> </style>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!