Commit 89ef67dd by Lin

feat: 项目更新

1 parent e3c9c2d3
Showing 207 changed files with 3296 additions and 1152 deletions
# 寮€鍙戠幆澧冮厤缃?
# 搴旂敤鍩烘湰淇℃伅
VITE_APP_NAME=寰簲鐢ㄦā鏉?VITE_APP_VERSION=1.0.0
# 寰簲鐢ㄥ悕绉帮紙涓庡熀搴ч厤缃繚鎸佷竴鑷达級
VITE_MICRO_APP_NAME=subapp-vue
# 鏈嶅姟绔彛
VITE_PORT=8081
# API 鍩虹璺緞
VITE_API_BASE_URL=http://localhost:3000/api
VITE_API_TIMEOUT=30000
# 璺敱鍩虹璺緞
VITE_BASE_URL=/subapp-vue
VITE_ROUTER_BASE=/subapp-vue
# 寰簲鐢ㄨ闂矾寰?VITE_PUBLIC_PATH=http://localhost:8081/
# 鏄惁涓哄紑鍙戞ā寮?VITE_USE_DEV_MODE=true
# 鏄惁鍚敤Mock鏁版嵁
VITE_USE_MOCK=false
# 鏄惁鍚敤璋冭瘯妯″紡
VITE_DEBUG=true
# 鍩哄骇搴旂敤鍦板潃
VITE_MAIN_APP_URL=http://localhost:8080
# 鏂囦欢涓婁紶鍦板潃
VITE_UPLOAD_URL=http://localhost:3000/api/upload
# 寮€鍙戠幆澧冩爣璇?NODE_ENV=development
# 鐢熶骇鐜閰嶇疆
# 鐢熶骇鐜鍩虹璺緞
VITE_BASE_URL=/subapp-vue/
// / <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
// qiankun 相关类型
declare global {
interface Window {
__INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
__POWERED_BY_QIANKUN__?: boolean;
}
}
sss
export {};
{
"name": "@venus/venus-agent-assisent",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
"preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vueuse/core": "catalog:",
"axios": "catalog:",
"pinia": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:"
}
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
<template>
<div id="micro-app" class="micro-app-container">
<header class="app-header">
<h1>🚀 Vue3 微前端子应用</h1>
<nav class="nav-menu">
<router-link class="nav-link" to="/">
首页
</router-link>
<router-link class="nav-link" to="/about">
关于
</router-link>
<router-link class="nav-link" to="/communication">
通信示例
</router-link>
<router-link class="nav-link" to="/user">
用户管理
</router-link>
<router-link class="nav-link" to="/settings">
系统设置
</router-link>
</nav>
</header>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition mode="out-in" name="fade">
<component :is="Component" />
</transition>
</router-view>
</main>
<footer class="app-footer">
<p>© 2025 Venus 微前端子应用模板</p>
</footer>
</div>
</template>
<script setup lang="ts">
import { onMounted } from "vue";
onMounted(() => {
console.log("Vue3 微应用已挂载");
});
</script>
<style scoped>
.micro-app-container {
display: flex;
flex-direction: column;
min-height: 100vh;
color: white;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.app-header {
padding: 1.5rem 2rem;
background: rgb(255 255 255 / 10%);
border-bottom: 1px solid rgb(255 255 255 / 20%);
backdrop-filter: blur(10px);
}
.app-header h1 {
margin: 0 0 1rem;
font-size: 1.8rem;
font-weight: 600;
}
.nav-menu {
display: flex;
gap: 1.5rem;
}
.nav-link {
padding: 0.5rem 1rem;
color: white;
text-decoration: none;
background: rgb(255 255 255 / 10%);
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.nav-link:hover {
background: rgb(255 255 255 / 20%);
transform: translateY(-2px);
}
.nav-link.router-link-active {
font-weight: 600;
background: rgb(255 255 255 / 30%);
}
.app-main {
flex: 1;
padding: 2rem;
}
.app-footer {
padding: 1rem 2rem;
text-align: center;
background: rgb(0 0 0 / 20%);
border-top: 1px solid rgb(255 255 255 / 10%);
}
/* 路由过渡动画 */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
import type { Router, RouteRecordRaw } from "vue-router";
import { createRouter as _createRouter, createWebHistory } from "vue-router";
const routes: RouteRecordRaw[] = [
{
path: "/",
name: "Home",
component: () => import("@/views/Home.vue"),
meta: {
title: "首页",
},
},
{
path: "/about",
name: "About",
component: () => import("@/views/About.vue"),
meta: {
title: "关于",
},
},
{
path: "/user",
name: "User",
component: () => import("@/views/User.vue"),
meta: {
title: "用户管理",
},
},
{
path: "/settings",
name: "Settings",
component: () => import("@/views/Settings.vue"),
meta: {
title: "系统设置",
},
},
{
path: "/communication",
name: "Communication",
component: () => import("@/views/Communication.vue"),
meta: {
title: "通信示例",
},
},
{
path: "/:pathMatch(.*)*",
name: "NotFound",
component: () => import("@/views/NotFound.vue"),
},
];
/**
* 创建路由实例
* @param base 路由 base 路径
*/
export function createRouter(base: string = "/"): Router {
const router = _createRouter({
history: createWebHistory(base),
routes,
});
// 路由守卫
router.beforeEach((to, _from, next) => {
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - Vue3 微应用`;
}
next();
});
router.afterEach((to, from) => {
console.log("[Vue3 微应用] 路由切换:", from.path, "->", to.path);
});
return router;
}
/* 全局样式 */
* {
box-sizing: border-box;
}
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
font-weight: 400;
line-height: 1.5;
color-scheme: light dark;
font-synthesis: none;
text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
margin: 0;
}
#app {
width: 100%;
min-height: 100vh;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgb(255 255 255 / 10%);
}
::-webkit-scrollbar-thumb {
background: rgb(255 255 255 / 30%);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgb(255 255 255 / 50%);
}
/* 选中文本样式 */
::selection {
color: white;
background: rgb(255 255 255 / 30%);
}
/* 响应式 */
@media (max-width: 768px) {
body {
font-size: 14px;
}
}
<template>
<div class="about-view">
<div class="content-card">
<h1>📖 关于本应用</h1>
<section class="section">
<h2>技术栈</h2>
<ul class="tech-list">
<li>
<strong>Vue 3</strong>
- 渐进式 JavaScript 框架
</li>
<li>
<strong>TypeScript</strong>
- 类型安全的 JavaScript 超集
</li>
<li>
<strong>Vite</strong>
- 新一代前端构建工具
</li>
<li>
<strong>Vue Router</strong>
- 官方路由管理器
</li>
<li>
<strong>Pinia</strong>
- 新一代状态管理库
</li>
<li>
<strong>qiankun</strong>
- 微前端框架
</li>
</ul>
</section>
<section class="section">
<h2>功能特性</h2>
<ul class="feature-list">
<li>✅ 支持独立运行和基座集成</li>
<li>✅ 完整的 TypeScript 支持</li>
<li>✅ 自动导入 API 和组件</li>
<li>✅ 热模块替换 (HMR)</li>
<li>✅ 路由懒加载</li>
<li>✅ CSS 样式隔离</li>
</ul>
</section>
<section class="section">
<h2>快速开始</h2>
<div class="code-block">
<pre>
<code>
# 安装依赖
pnpm install
# 启动开发服务器
pnpm dev
# 构建生产版本
pnpm build
</code>
</pre>
</div>
</section>
</div>
</div>
</template>
<script setup lang="ts">
// About 页面
</script>
<style scoped>
.about-view {
max-width: 900px;
margin: 0 auto;
}
.content-card {
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 2rem;
font-size: 2rem;
}
.section {
margin-bottom: 2rem;
}
.section h2 {
margin: 0 0 1rem;
font-size: 1.5rem;
color: rgb(255 255 255 / 95%);
}
.tech-list,
.feature-list {
padding: 0;
margin: 0;
list-style: none;
}
.tech-list li,
.feature-list li {
padding: 0.5rem 0;
line-height: 1.6;
opacity: 0.9;
}
.code-block {
padding: 1.5rem;
overflow-x: auto;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.5rem;
}
.code-block pre {
margin: 0;
font-family: "Courier New", monospace;
font-size: 0.9rem;
line-height: 1.6;
}
.code-block code {
color: #a8e6cf;
}
</style>
import { resolve } from "node:path";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { defineConfig } from "vite";
import qiankun from "vite-plugin-qiankun";
const PORT = 8081;
const APP_NAME = "subapp-vue"; // 与基座配置的 name 一致
export default defineConfig(({ mode, command }) => {
const isDev = mode === "development";
const isServe = command === "serve";
return {
base: isDev && isServe ? `http://localhost:${PORT}/` : `/${APP_NAME}/`, // 生产环境使用应用名作为基础路径
plugins: [
vue(),
vueJsx(),
// 自动导入 Vue 相关函数
AutoImport({
imports: [ "vue", "vue-router", "pinia" ],
dts: "src/auto-imports.d.ts",
eslintrc: {
enabled: false,
},
}),
// 自动导入组件
Components({
dts: "src/components.d.ts",
}),
// qiankun 插件配置
qiankun(APP_NAME, {
useDevMode: isDev, // 根据实际环境动态设置
}),
],
resolve: {
alias: {
"@": resolve(import.meta.dirname, "src"),
},
},
server: {
port: PORT,
cors: true, // 允许跨域
host: true,
origin: `http://localhost:${PORT}`, // 设置资源加载的 origin
headers: {
"Access-Control-Allow-Origin": "*", // 允许所有来源
},
},
build: {
target: "esnext",
minify: false, // 开发环境不压缩,便于调试
cssCodeSplit: false, // css 不拆分
rollupOptions: {
output: {
// qiankun 需要的输出格式
format: "umd",
// UMD 库名称,必须与应用名称一致
name: `qiankunApp_${APP_NAME.replaceAll("-", "_")}`,
entryFileNames: "assets/[name].js",
chunkFileNames: "assets/[name].[hash].js",
assetFileNames: "assets/[name].[hash].[ext]",
},
},
},
};
});
VITE_APP_VERSION=1.0.0
VITE_MICRO_APP_NAME=assisant
VITE_API_TIMEOUT=30000
VITE_BASE_URL=/assisant
VITE_ROUTER_BASE=/assisant
VITE_USE_MOCK=false
VITE_DEBUG=true
......@@ -89,13 +89,11 @@ micro-app-template/
在启动前,请确保配置正确(已在本次更新中修复):
**子应用配置检查:**
- ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/`
- ✅ `src/router/index.ts` - 导出 `createRouter` 函数
- ✅ `src/main.ts` - 动态创建路由实例
**基座配置检查:**
- ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081`
- ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>`
......@@ -109,7 +107,6 @@ pnpm dev
子应用会在 `http://localhost:8081` 启动
**验证:**
- 访问 `http://localhost:8081` 应显示子应用
- 控制台显示 "独立运行模式"
......@@ -123,7 +120,6 @@ pnpm dev
基座会在 `http://localhost:8080` 启动
**验证:**
- 控制台显示 "[qiankun] 微前端框架已启动"
### 3. 在基座中访问子应用
......@@ -131,7 +127,6 @@ pnpm dev
访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用
**预期结果:**
- 看到子应用内容(紫色渐变背景)
- 控制台显示生命周期日志
- 运行模式显示 "🔗 基座模式"
......@@ -153,7 +148,7 @@ const PORT = 8081; // 修改为你想要的端口
1. 在 `vite.config.ts` 中修改 `APP_NAME`:
```typescript
const APP_NAME = "your-app-name";
const APP_NAME = 'your-app-name';
```
2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置:
......@@ -208,12 +203,12 @@ pnpm dev
使用以下方式判断应用是否在 qiankun 环境中运行:
```typescript
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log("在基座中运行");
console.log('在基座中运行');
} else {
console.log("独立运行");
console.log('独立运行');
}
```
......@@ -222,13 +217,11 @@ if (qiankunWindow.__POWERED_BY_QIANKUN__) {
### 1. 子应用无法加载(白屏)
**原因:**
- 子应用未启动
- entry 地址配置错误
- 容器 ID 不存在
**解决:**
```bash
# 确认子应用运行
curl http://localhost:8081
......@@ -245,13 +238,11 @@ entry: 'http://localhost:8081' // ✅ 使用完整 URL
### 2. CORS 错误
**控制台显示:**
```
Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
```
**解决:**
- 确认子应用 `vite.config.ts` 中 `cors: true`
- 确认 headers 配置正确
- 重启子应用服务
......@@ -259,15 +250,15 @@ Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
### 3. 路由跳转异常
**原因:**
- 路由 base 配置错误
- `routerBase` 未正确传递
**解决:**
```typescript
// ✅ 已修复:子应用动态创建路由
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ ? props.routerBase || "/subapp-vue" : "/";
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? (props.routerBase || '/subapp-vue')
: '/';
const router = createRouter(routerBase);
```
......@@ -280,20 +271,18 @@ const router = createRouter(routerBase);
### 5. 生命周期未触发
**原因:**
- 应用名称不一致
- 生命周期钩子未正确导出
**解决:**
```typescript
// vite.config.ts
qiankun("subapp-vue"); // 必须与基座配置一致
qiankun('subapp-vue') // 必须与基座配置一致
// main.ts
export async function bootstrap() {}
export async function mount(props) {}
export async function unmount(props) {}
export async function bootstrap() { }
export async function mount(props) { }
export async function unmount(props) { }
```
**详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
......@@ -305,3 +294,4 @@ MIT
## 🤝 贡献
欢迎提交 Issue 和 Pull Request!
# 子应用使用 GSC Request 指南
## 概述
子应用可以通过基座下发的 GSC Request 实例来发起请求,无需重复配置。所有请求都会使用基座从配置中心获取的统一配置。
## 快速开始
### 1. 在组件中使用(推荐方式)
#### 方式一:使用封装的工具函数(最简单)
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { gscPost, gscGet } from '@/utils/gscRequest';
import { ElMessage } from 'element-plus';
const loading = ref(false);
const data = ref(null);
// 发起 POST 请求
const fetchData = async () => {
try {
loading.value = true;
const response = await gscPost('/api/data', {
name: 'test',
page: 1,
});
data.value = response;
ElMessage.success('获取数据成功');
} catch (error) {
console.error('请求失败:', error);
ElMessage.error('获取数据失败');
} finally {
loading.value = false;
}
};
// 发起 GET 请求
const getUserInfo = async () => {
try {
const response = await gscGet('/user/info');
console.log('用户信息:', response);
} catch (error) {
console.error('获取用户信息失败:', error);
}
};
onMounted(() => {
fetchData();
});
</script>
<template>
<div>
<el-button :loading="loading" @click="fetchData">获取数据</el-button>
<pre>{{ data }}</pre>
</div>
</template>
```
#### 方式二:使用全局属性(在 Options API 中)
```vue
<script>
export default {
data() {
return {
loading: false,
data: null,
};
},
methods: {
async fetchData() {
try {
this.loading = true;
// 通过全局属性访问
const request = await this.$gscRequest.getRequest();
const response = await request.post('/api/data', { name: 'test' });
this.data = response;
} catch (error) {
console.error('请求失败:', error);
} finally {
this.loading = false;
}
},
},
mounted() {
this.fetchData();
},
};
</script>
```
#### 方式三:直接获取 Request 实例(高级用法)
```vue
<script setup lang="ts">
import { onMounted } from 'vue';
import { getGscRequest } from '@/utils/gscRequest';
onMounted(async () => {
try {
const request = await getGscRequest();
// 直接使用 request 实例的所有方法
const response = await request.post('/api/data', {});
console.log('响应:', response);
} catch (error) {
console.error('请求失败:', error);
}
});
</script>
```
### 2. 在 API 文件中使用
创建 `src/api/user.ts`:
```typescript
import { gscPost, gscGet } from '@/utils/gscRequest';
/**
* 用户登录
*/
export async function login(username: string, password: string) {
return gscPost('/login', {
username,
password,
});
}
/**
* 获取用户信息
*/
export async function getUserInfo() {
return gscGet('/user/info');
}
/**
* 更新用户信息
*/
export async function updateUserInfo(data: any) {
return gscPost('/user/update', data);
}
```
在组件中使用:
```vue
<script setup lang="ts">
import { login, getUserInfo } from '@/api/user';
const handleLogin = async () => {
try {
const response = await login('admin', '123456');
console.log('登录成功:', response);
} catch (error) {
console.error('登录失败:', error);
}
};
</script>
```
### 3. 带配置的请求
```typescript
import { gscPost } from '@/utils/gscRequest';
// 带配置的 POST 请求
const response = await gscPost(
'/api/data',
{ name: 'test' },
{
returnAll: true, // 返回完整响应(包括 headers 等)
timeout: 10000, // 超时时间(毫秒)
},
);
```
## 完整示例
### 示例:在列表页面中使用
```vue
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { gscPost, gscGet } from '@/utils/gscRequest';
import { ElMessage, ElMessageBox } from 'element-plus';
interface ListItem {
id: number;
name: string;
status: boolean;
}
const loading = ref(false);
const tableData = ref<ListItem[]>([]);
const searchForm = ref({
name: '',
status: '',
});
// 获取列表数据
const fetchList = async () => {
try {
loading.value = true;
const response = await gscPost('/api/list', {
...searchForm.value,
page: 1,
pageSize: 10,
});
tableData.value = response.data || [];
} catch (error) {
console.error('获取列表失败:', error);
ElMessage.error('获取列表失败');
} finally {
loading.value = false;
}
};
// 删除数据
const handleDelete = async (id: number) => {
try {
await ElMessageBox.confirm('确定要删除这条数据吗?', '提示', {
type: 'warning',
});
await gscPost('/api/delete', { id });
ElMessage.success('删除成功');
await fetchList(); // 刷新列表
} catch (error) {
if (error !== 'cancel') {
console.error('删除失败:', error);
ElMessage.error('删除失败');
}
}
};
// 更新状态
const handleStatusChange = async (id: number, status: boolean) => {
try {
await gscPost('/api/updateStatus', { id, status });
ElMessage.success('状态更新成功');
} catch (error) {
console.error('更新状态失败:', error);
ElMessage.error('更新状态失败');
}
};
onMounted(() => {
fetchList();
});
</script>
<template>
<div>
<el-table :data="tableData" :loading="loading">
<el-table-column prop="name" label="名称" />
<el-table-column prop="status" label="状态">
<template #default="{ row }">
<el-switch
:model-value="row.status"
@change="(val) => handleStatusChange(row.id, val)"
/>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="{ row }">
<el-button
type="danger"
size="small"
@click="handleDelete(row.id)"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
```
## 错误处理
### 基本错误处理
```typescript
import { gscPost } from '@/utils/gscRequest';
try {
const response = await gscPost('/api/data', {});
// 处理成功响应
} catch (error) {
// 处理错误
if (error instanceof Error) {
console.error('错误信息:', error.message);
}
// 可以根据错误类型进行不同处理
}
```
### 统一错误处理(推荐)
创建 `src/utils/requestErrorHandler.ts`:
```typescript
import { ElMessage } from 'element-plus';
export function handleRequestError(error: any) {
if (error?.response) {
// HTTP 错误
const status = error.response.status;
switch (status) {
case 401:
ElMessage.error('未授权,请重新登录');
// 可以跳转到登录页
break;
case 403:
ElMessage.error('没有权限访问');
break;
case 404:
ElMessage.error('请求的资源不存在');
break;
case 500:
ElMessage.error('服务器错误');
break;
default:
ElMessage.error(error.response.data?.message || '请求失败');
}
} else if (error?.message) {
// 其他错误
ElMessage.error(error.message);
} else {
ElMessage.error('网络错误,请稍后重试');
}
}
```
使用:
```typescript
import { gscPost } from '@/utils/gscRequest';
import { handleRequestError } from '@/utils/requestErrorHandler';
const fetchData = async () => {
try {
const response = await gscPost('/api/data', {});
return response;
} catch (error) {
handleRequestError(error);
throw error;
}
};
```
## 注意事项
1. **环境检查**:GSC Request 只在 qiankun 环境中可用,独立运行时无法使用
2. **异步初始化**:Request 实例是异步获取的,确保在使用前已初始化
3. **错误处理**:建议对所有请求添加错误处理
4. **类型安全**:虽然使用了类型断言,但实际运行时 Request 实例确实有 post/get 等方法
## 与基座 API 的对比
基座应用中的使用方式:
```typescript
// 基座:config/gscrequest.ts
import gscPost from '@/config/gscrequest';
const response = await gscPost('/api/data', {});
```
子应用中的使用方式:
```typescript
// 子应用:utils/gscRequest.ts
import { gscPost } from '@/utils/gscRequest';
const response = await gscPost('/api/data', {});
```
**使用方式完全一致!** 这样可以保持代码风格统一。
## 常见问题
### Q: 为什么在独立运行时无法使用?
A: GSC Request 实例是通过基座的配置中心获取的,只有在 qiankun 环境中才能通过 props 获取。独立运行时需要自己配置请求工具。
### Q: 如何判断 Request 是否已初始化?
A: 使用 `gscRequestManager.isInitialized()` 方法:
```typescript
import { gscRequestManager } from '@/utils/gscRequest';
if (gscRequestManager.isInitialized()) {
// Request 已初始化,可以安全使用
}
```
### Q: 请求失败时如何获取详细错误信息?
A: 错误对象中通常包含 `response` 属性,可以从中获取详细信息:
```typescript
try {
await gscPost('/api/data', {});
} catch (error: any) {
console.error('状态码:', error.response?.status);
console.error('错误信息:', error.response?.data);
console.error('请求配置:', error.config);
}
```
// / <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
const component: DefineComponent<{}, {}, any>;
export default component;
}
// qiankun 相关类型
declare global {
interface Window {
__POWERED_BY_QIANKUN__?: boolean;
__INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
}
interface Window {
__INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
__POWERED_BY_QIANKUN__?: boolean;
}
}
export {};
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SCRM 微前端主应用</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
<html lang="zh-CN" sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<meta name="description" content="" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "@venus/venus-micro-app",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
"preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"axios": "catalog:",
"pinia": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:"
}
"name": "@venus/venus-agentic-assisant",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
"postbuild": "node ../../../../scripts/copy-dist-to-root.mjs",
"preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vue-office/docx": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/excel": "catalog:",
"@js-preview/excel": "catalog:",
"@vue-office/pptx": "catalog:",
"@js-preview/pdf": "catalog:",
"@js-preview/docx": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@venus/tailwind-config": "workspace:*",
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"axios": "catalog:",
"element-plus": "catalog:",
"pinia": "catalog:",
"tailwindcss": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:",
"glsk-oss-jssdk": "catalog:",
"sass": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:"
}
}
export { default } from '@venus/tailwind-config/postcss';
<script setup lang="ts">
import { onMounted } from 'vue';
onMounted(() => {
// console.log('Vue3 微应用已挂载');
});
</script>
<template>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</main>
</template>
<style scoped>
.app-main {
flex: 1;
}
/* 路由过渡动画 */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
import { gscPost} from '@/utils/gscRequest';
/**
* 质检规则列表查询
*/
export async function inspectionRuleList(data: any) {
try {
const response = await gscPost('/inspectionRule/findPageInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则新增
*/
export async function addInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/addInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则列表修改
*/
export async function updateInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/updateInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检规则列表删除
*/
export async function deleteInspectionRule(data: any) {
try {
const response = await gscPost('/inspectionRule/deleteInspectionRule', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版列表查询
*/
export async function inspectionTemplateList(data: any) {
try {
const response = await gscPost('/inspectionTemplate/findPageInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版新增
*/
export async function addInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/saveInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版修改
*/
export async function updateInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/updateInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 质检模版删除
*/
export async function deleteInspectionTemplate(data: any) {
try {
const response = await gscPost('/inspectionTemplate/deleteInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体列表查询
*/
export async function trainingPlanList(data: any) {
try {
const response = await gscPost('/trainingPlan/findPageTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体新增
*/
export async function addTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/addTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体修改
*/
export async function updateTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/updateTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体删除
*/
export async function deleteTrainingPlan(data: any) {
try {
const response = await gscPost('/trainingPlan/deleteTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 培训智能体详情
*/
export async function ftrainingPlanDetail(data: any) {
try {
const response = await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
return response;
} catch (error) {
throw error;
}
}
/**
* 通用知识分类列表
*/
export async function generalKnowledgeList(data: any) {
try {
const response = await gscPost('/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList', data);
return response;
} catch (error) {
throw error;
}
}
/*
* 复盘智能体提示词模板查询
*/
export async function getPromptTemplate(data: any) {
try {
const response = await gscPost('/reviewAgentPromptTemplate/findPromptTemplate', data);
return response;
} catch (error) {
throw error;
}
}
/*
* 复盘智能体提示词模板更新
*/
export async function updatePromptTemplate(data: any) {
try {
const response = await gscPost('/reviewAgentPromptTemplate/updatePromptTemplate', data);
return response;
} catch (error) {
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 岗位助理列表
*/
export async function assistantList(data: any) {
try {
const response = await gscPost('/jobAgentInfo/findPageAgentInfo', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理详情
*/
export async function assistantDetail(data: any) {
try {
const response = await gscPost('/jobAgentDetail/detailById', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理创建
*/
export async function assistantCreate(data: any) {
try {
const response = await gscPost('/jobAgentInfo/create', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理更新
*/
export async function assistantUpdate(data: any) {
try {
const response = await gscPost('/jobAgentInfo/update', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 岗位助理状态修改
*/
export async function assistantStatus(data: any) {
try {
const response = await gscPost('/jobAgentInfo/forbiddenOrEnable', data);
return response;
} catch (error) {
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 企微部门模块树
*/
export async function findDeptTree(data: any) {
try {
const response = await gscPost('/entmicroDepartment/findDeptTree', data);
return response;
} catch (error) {
throw error;
}
}
import { gscPost} from '@/utils/gscRequest';
/**
* 素材分组列表
*/
export async function findCategoryList(data: any) {
try {
const response = await gscPost('/knowledgeCategory/findCategoryList', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 素材分组新增
*/
export async function addCategory(data: any) {
try {
const response = await gscPost('/knowledgeCategory/addCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材分组修改
*/
export async function updateCategory(data: any) {
try {
const response = await gscPost('/knowledgeCategory/updateCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 分组列表包含的素材列表
*/
export async function findCategoryWithMaterialList(data: any) {
try {
const response = await gscPost('/knowledgeCategory/findCategoryWithMaterialList', data);
return response;
} catch (error) {
throw error;
}
}
/**
* 素材列表
*/
export async function findPageKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/findPageKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材编辑
*/
export async function updateKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/updateKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材上传
*/
export async function saveKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/saveKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
/**
* 素材删除
*/
export async function deleteKnowledgeMaterial(data: any) {
try {
const response = await gscPost('/knowledgeMaterial/deleteKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
}
<template>
<div class="card-list w-full flex flex-nowrap gap-6">
<div
class="card-item flex-1 min-w-[202.5px] rounded-[10px] box-border shadow-[0_4px_12px_0_#525b6629]"
:style="{ minHeight: cardHeight }"
v-for="(item, index) in data"
:key="index"
>
<img class="rounded-t-[10px]" :src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`" alt="background">
<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>
<div class="flex justify-between" v-for="value in item.desc">
<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>
</template>
<script setup lang="ts">
import { computed, PropType } from 'vue';
interface DataItem {
iconUrl: string;
name: string;
desc: string[];
}
const props = defineProps({
data: {
type: Array as PropType<DataItem[]>,
required: true,
},
source: {
type: String as PropType<'train' | 'raplay' | 'other'>,
required: false,
default: 'other',
},
});
const cardHeight = computed(() => {
if (props.source === 'train') return '246px';
if (props.source === 'raplay') return '204px';
return '182px';
});
console.log('[CustomCardList] data', props.data);
</script>
<template>
<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">
<p class="text-[14px] font-medium text-[#2F3133] ml-[12px]">{{ title }}</p>
</div>
</template>
<script setup>
const props = defineProps({
title: {
type: String,
required: true,
},
icon: {
type: String,
required: false,
},
});
</script>
<template>
<div class="pl-2">
<div
v-for="(item, index) in workflowSteps"
:key="index"
class="relative pb-8 last:pb-0"
>
<!-- 连接线 -->
<div
v-if="index !== workflowSteps.length - 1"
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">
<!-- 步骤数字 -->
<span
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>
<!-- 步骤内容 -->
<div class="ml-4 min-w-0 flex-1">
<h4 class="mb-1 text-[14px] font-normal text-[#2F3133]">
{{ item.title }}
</h4>
<div v-if="Array.isArray(item.desc)">
<p
class="mt-[4px] text-[12px] font-normal text-[#969AA3]"
v-for="value in item.desc"
>
<span
class="mb-[2px] mr-[4px] inline-block h-[5px] w-[5px] rounded-[3px] bg-[#1956FE]"
></span>
{{ value }}
</p>
</div>
<div v-else>
<p class="mt-[4px] text-[12px] font-normal text-[#969AA3]">
{{ item.desc }}
</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
workflowSteps: {
type: Array,
required: true,
},
});
</script>
import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";
import type { App as VueApp } from "vue";
import { createApp } from "vue";
import { createPinia } from "pinia";
import { qiankunWindow, renderWithQiankun } from "vite-plugin-qiankun/dist/helper";
import App from "./App.vue";
import { createRouter } from "./router";
import "./style.css";
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper';
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 { createPinia } from 'pinia';
import {
qiankunWindow,
renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue';
import { createRouter } from './router';
import 'element-plus/dist/index.css';
import './assets/style.css';
let app: null | VueApp<Element> = null;
let router: any = null;
......@@ -20,36 +24,60 @@ let router: any = null;
* @param props qiankun 传递的参数
*/
async function render(props: QiankunProps = {}) {
const { container } = props;
app = createApp(App);
// 配置 Pinia
app.use(createPinia());
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ ? props.routerBase || "/subapp-vue" : "/";
router = createRouter(routerBase);
app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication;
}
// 挂载应用
const containerEl = container ? container.querySelector("#app") : document.querySelector("#app");
if (containerEl) {
app.mount(containerEl as Element);
} else {
console.error("[Vue3 微应用] 挂载容器未找到");
}
const { container } = props;
app = createApp(App);
// 配置 Pinia
app.use(createPinia());
// 配置 Element-Plus
app.use(ElementPlus, {
//改中文
locale: zhCn
});
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? props.routerBase || '/assisant/'
: '/';
router = createRouter(routerBase);
app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication;
}
// 初始化 GSC Request(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.getGscRequest) {
try {
const { gscRequestManager } = await import('./utils/gscRequest');
await gscRequestManager.init(props);
// 将 GSC Request 管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$gscRequest = gscRequestManager;
// console.log('[子应用] GSC Request 管理器已初始化并挂载');
} catch (error) {
console.error('[子应用] GSC Request 管理器初始化失败:', error);
}
}
// 挂载应用
const containerEl = container
? container.querySelector('#app')
: document.querySelector('#app');
if (containerEl) {
app.mount(containerEl as Element);
} else {
console.error('[Vue3 微应用] 挂载容器未找到');
}
}
/**
......@@ -57,8 +85,7 @@ async function render(props: QiankunProps = {}) {
* 直接访问子应用时,不是通过基座加载
*/
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log("独立运行模式");
render();
render();
}
/**
......@@ -66,7 +93,7 @@ if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
* 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子
*/
export async function bootstrap() {
console.log("[Vue3 微应用] bootstrap");
// console.log('[Vue3 微应用钩子] bootstrap');
}
/**
......@@ -74,8 +101,8 @@ export async function bootstrap() {
* 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法
*/
export async function mount(props: QiankunProps) {
console.log("Vue3 微应用 mount", props);
render(props);
// console.log('Vue3 微应用钩子 mount', props);
render(props);
}
/**
......@@ -83,21 +110,24 @@ export async function mount(props: QiankunProps) {
* 应用每次切出/卸载都会调用 unmount 方法
*/
export async function unmount(props: QiankunProps) {
console.log("[Vue3 微应用] unmount", props);
// 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.destroy();
}
if (app) {
app.unmount();
app = null;
}
if (router) {
router = null;
}
console.log('[子应用] unmount', props);
// 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.destroy();
// 销毁 GSC Request 管理器
const { gscRequestManager } = await import('./utils/gscRequest');
gscRequestManager.destroy();
}
if (app) {
app.unmount();
app = null;
}
if (router) {
router = null;
}
}
/**
......@@ -105,13 +135,13 @@ export async function unmount(props: QiankunProps) {
* 主应用向子应用下发新的props时触发
*/
export async function update(props: QiankunProps) {
console.log("[Vue3 微应用] update", props);
console.log('[Vue3 微应用] update', props);
}
// 使用 vite-plugin-qiankun 提供的渲染函数
renderWithQiankun({
bootstrap,
mount,
unmount,
update,
bootstrap,
mount,
unmount,
update,
});
import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: '首页',
},
},
{
path: '/managekonw',
name: 'ManageKonw',
component: () => import('@/views/ManageKonw/index.vue'),
meta: {
title: '知识管理',
},
},
{
path: '/assistant',
name: 'Assistant',
component: () => import('@/views/Assistant/index.vue'),
meta: {
title: '岗位助理配置',
},
},
{
path: '/manageagentic',
name: 'ManageAgentic',
component: () => import('@/views/ManageAgentic/index.vue'),
meta: {
title: '智能体管理',
},
},
{
path: '/assistant/add',
name: 'AssistantAdd',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '新增智能体',
},
},
{
path: '/assistant/edit/:id',
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑',
},
},
{
path: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: '用户管理',
},
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
meta: {
title: '系统设置',
},
},
{
path: '/communication',
name: 'Communication',
component: () => import('@/views/Communication.vue'),
meta: {
title: '通信示例',
},
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
},
];
/**
* 创建路由实例
* @param base 路由 base 路径
*/
export function createRouter(base: string = '/'): Router {
const router = _createRouter({
history: createWebHistory(base),
routes,
});
// 路由守卫
router.beforeEach((to, _from, next) => {
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title}`;
}
next();
});
router.afterEach((to, from) => {
console.log('[Vue3 微应用] 路由切换:', from.path, '->', to.path);
});
return router;
}
/**
* glsk-oss-jssdk 类型声明
*/
declare module 'glsk-oss-jssdk' {
/**
* 上传结果接口
*/
export interface MultipartUploadResult {
/** 阿里云地址 */
aliyunAddress: string;
/** 附件名称 */
attachment: string;
/** 其他可能的字段 */
[key: string]: any;
}
/**
* OSS API 类
*/
class GlOssApi {
/**
* 分片上传文件
* @param file 要上传的文件
* @param onSuccess 成功回调函数
* @param onError 失败回调函数
*/
multipartUpload(
file: File,
onSuccess: (result: MultipartUploadResult) => void,
onError: (error: Error) => void,
): void;
}
export default GlOssApi;
}
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
/**
* 获取子应用的基础 URL
* 在微前端环境中,返回子应用的实际域名和端口
* 在独立运行时,返回当前域名
*/
/**
* 获取子应用的基础 URL
* 在微前端环境中,返回子应用的实际域名和端口
* 在独立运行时,返回当前域名
*/
export function getSubAppBaseUrl(): string {
// 如果在 qiankun 环境中
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
// qiankun 会注入 __INJECTED_PUBLIC_PATH_BY_QIANKUN__,包含子应用的公共路径
const publicPath = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
if (publicPath) {
// 从 publicPath 中提取基础 URL
try {
// 尝试将 publicPath 解析为完整 URL
const url = new URL(publicPath);
// 如果 publicPath 是完整 URL(包含协议),返回其 origin
if (url.protocol.startsWith('http')) {
return url.origin;
}
} catch {
// URL 解析失败,说明 publicPath 可能是相对路径,继续下面的处理
}
// 在开发环境中,子应用通常运行在独立端口(如 8081)
const isDev = (import.meta as any).env?.MODE === 'development';
if (isDev) {
// 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致)
const devPort = '8081';
const host = window.location.hostname;
return `http://${host}:${devPort}`;
}
// 生产环境:如果 publicPath 是相对路径,说明可能是同域部署
// 此时使用当前域名即可(资源应该在同一域名下)
return window.location.origin;
}
// 如果无法从 publicPath 获取,根据环境判断
const isDev = (import.meta as any).env?.MODE === 'development';
if (isDev) {
// 开发环境:使用默认端口
const host = window.location.hostname;
return `http://${host}:8081`;
}
// 生产环境:使用当前域名
return window.location.origin;
}
// 独立运行时,返回当前域名
return window.location.origin;
}
/**
* 处理图片资源路径,确保使用子应用自己的域名
* @param imagePath 图片路径,可以是相对路径(如 /images/xxx.png)或绝对路径(如 http://xxx/images/xxx.png)
* @returns 处理后的完整图片 URL
*/
export function getImageUrl(imagePath: string): string {
if (!imagePath) {
return '';
}
// 如果已经是完整的 URL(包含 http:// 或 https://),直接返回
if (/^https?:\/\//.test(imagePath)) {
// 如果是完整 URL,检查是否是子应用的域名
try {
const url = new URL(imagePath);
const baseUrl = getSubAppBaseUrl();
const baseUrlObj = new URL(baseUrl, window.location.href);
// 如果 URL 的域名和子应用的域名不同,需要替换为子应用的域名
if (url.origin !== baseUrlObj.origin) {
// 提取路径部分,使用子应用的域名
return `${baseUrlObj.origin}${url.pathname}${url.search}${url.hash}`;
}
return imagePath;
} catch {
return imagePath;
}
}
// 如果是相对路径(以 / 开头),拼接子应用的基础 URL
if (imagePath.startsWith('/')) {
const baseUrl = getSubAppBaseUrl();
return `${baseUrl}${imagePath}`;
}
// 如果是相对路径(不以 / 开头),需要根据当前路径处理
// 这里假设是相对于 public 目录的路径
const baseUrl = getSubAppBaseUrl();
return `${baseUrl}/${imagePath}`;
}
import { onUnmounted } from "vue";
import { onUnmounted } from 'vue';
/**
* 全局状态接口定义(与基座保持一致)
*/
export interface GlobalState {
config: {
apiBaseUrl: string;
timeout: number;
};
notifications: Notification[];
theme: {
mode: "dark" | "light";
primaryColor: string;
};
user: null | {
avatar: string;
id: string;
name: string;
permissions: string[];
role: string;
};
config: {
apiBaseUrl: string;
timeout: number;
};
notifications: Notification[];
theme: {
mode: 'dark' | 'light';
primaryColor: string;
};
user: null | {
avatar: string;
id: string;
name: string;
permissions: string[];
role: string;
};
}
/**
* 通知消息接口
*/
export interface Notification {
from?: string;
id: string;
message: string;
timestamp: number;
title: string;
type: "error" | "info" | "success" | "warning";
from?: string;
id: string;
message: string;
timestamp: number;
title: string;
type: 'error' | 'info' | 'success' | 'warning';
}
/**
* qiankun Props 类型定义
*/
export interface QiankunProps {
[key: string]: any;
container?: HTMLElement;
onGlobalStateChange?: (
callback: (state: GlobalState, prev: GlobalState) => void,
fireImmediately?: boolean,
) => void;
routerBase?: string;
setGlobalState?: (state: Partial<GlobalState>) => void;
[key: string]: any;
container?: HTMLElement;
onGlobalStateChange?: (
callback: (state: GlobalState, prev: GlobalState) => void,
fireImmediately?: boolean,
) => void;
routerBase?: string;
setGlobalState?: (state: Partial<GlobalState>) => void;
}
/**
* 子应用通信管理器
*/
class SubAppCommunicationManager {
private currentState: GlobalState | null = null; // 缓存当前状态
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> = [];
private props: null | QiankunProps = null;
private unsubscribe: (() => void) | null = null;
/**
* 销毁
*/
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
this.listeners = [];
this.props = null;
console.log("[子应用通信] 通信管理器已销毁");
}
/**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/**
* 初始化通信管理器
* @param props qiankun 传递的 props
*/
init(props: QiankunProps) {
this.props = props;
// 监听全局状态变化
if (props.onGlobalStateChange) {
const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => {
console.log("[子应用通信] 全局状态变化:", state, prev);
// 缓存当前状态
this.currentState = state;
// 触发所有监听器
this.listeners.forEach((listener) => {
listener(state, prev);
});
},
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
);
// 只在返回值是函数时才赋值
if (typeof unsubscribeFn === "function") {
this.unsubscribe = unsubscribeFn;
}
}
console.log("[子应用通信] 通信管理器初始化完成");
// 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递
setTimeout(() => {
if (this.props?.onGlobalStateChange) {
console.log("[子应用通信] 二次确认全局状态同步");
}
}, 100);
}
/**
* 监听全局状态变化
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(callback: (state: GlobalState, prev: GlobalState) => void): () => void {
this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) {
console.log("[子应用通信] 立即触发回调,使用缓存的全局状态");
callback(this.currentState, {} as GlobalState);
}
return () => {
const index = this.listeners.indexOf(callback);
if (index !== -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* 向基座发送通知
* @param notification 通知消息
*/
sendNotification(notification: Omit<Notification, "id" | "timestamp">) {
if (!this.props?.setGlobalState) {
console.warn("[子应用通信] 无法发送通知,setGlobalState 方法不可用");
return;
}
// 获取当前通知列表(需要通过 props 或缓存获取)
// 这里简化处理,直接通过 state 添加
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
from: notification.from || "Vue子应用",
};
// 通过修改全局状态来添加通知
// 注意:这里需要基座的 communication manager 来处理通知添加逻辑
// 所以我们实际上是触发一个状态变化,让基座来处理
this.setGlobalState({
notifications: [ newNotification ] as any, // 基座会合并到现有通知列表
});
}
/**
* 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) {
this.props.setGlobalState(state);
console.log("[子应用通信] 全局状态已更新:", state);
} else {
console.warn("[子应用通信] setGlobalState 方法不可用");
}
}
private currentState: GlobalState | null = null; // 缓存当前状态
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[];
private props: null | QiankunProps = null;
private unsubscribe: (() => void) | null = null;
/**
* 销毁
*/
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
this.listeners = [];
this.props = null;
}
/**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/**
* 初始化通信管理器
* @param props qiankun 传递的 props
*/
init(props: QiankunProps) {
this.props = props;
// 监听全局状态变化
if (props.onGlobalStateChange) {
const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => {
// 缓存当前状态
this.currentState = state;
// 触发所有监听器
this.listeners.forEach((listener) => {
listener(state, prev);
});
},
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
);
// 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') {
this.unsubscribe = unsubscribeFn;
}
}
}
/**
* 监听全局状态变化
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) {
callback(this.currentState, {} as GlobalState);
}
return () => {
const index = this.listeners.indexOf(callback);
if (index !== -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* 向基座发送通知
* @param notification 通知消息
*/
sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
if (!this.props?.setGlobalState) {
return;
}
// 获取当前通知列表(需要通过 props 或缓存获取)
// 这里简化处理,直接通过 state 添加
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
from: notification.from || 'Vue子应用',
};
// 通过修改全局状态来添加通知
// 注意:这里需要基座的 communication manager 来处理通知添加逻辑
// 所以我们实际上是触发一个状态变化,让基座来处理
this.setGlobalState({
notifications: [newNotification] as any, // 基座会合并到现有通知列表
});
}
/**
* 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) {
this.props.setGlobalState(state);
}
}
}
// 导出单例
......@@ -189,24 +175,30 @@ export const subAppCommunication = new SubAppCommunicationManager();
* Vue 组合式 API - 使用全局状态
* @param callback 状态变化回调
*/
export function useGlobalState(callback: (state: GlobalState, prev: GlobalState) => void) {
const unsubscribe = subAppCommunication.onStateChange(callback);
export function useGlobalState(
callback: (state: GlobalState, prev: GlobalState) => void,
) {
const unsubscribe = subAppCommunication.onStateChange(callback);
// 在组件卸载时自动取消订阅
onUnmounted(() => {
unsubscribe();
});
// 在组件卸载时自动取消订阅
onUnmounted(() => {
unsubscribe();
});
return unsubscribe;
return unsubscribe;
}
/**
* 便捷方法:发送通知到基座
*/
export function notify(type: Notification["type"], title: string, message: string) {
subAppCommunication.sendNotification({
type,
title,
message,
});
export function notify(
type: Notification['type'],
title: string,
message: string,
) {
subAppCommunication.sendNotification({
type,
title,
message,
});
}
import type { Request } from 'glsk-toolkit';
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
/**
* GSC Request 管理器
* 用于管理从基座获取的 Request 实例
*/
class GscRequestManager {
private requestInstance: Request | null = null;
private getGscRequestFn: (() => Promise<Request>) | null = null;
private initPromise: Promise<Request> | null = null;
/**
* 初始化 GSC Request(在子应用 render 函数中调用)
* @param props qiankun 传递的 props
*/
async init(props: QiankunProps) {
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;
}
}
/**
* 获取 GSC Request 实例
* @returns Promise<Request> Request 实例
*/
async getRequest(): Promise<Request> {
// 如果已有实例,直接返回
if (this.requestInstance) {
return this.requestInstance;
}
// 如果有获取函数,尝试获取
if (this.getGscRequestFn) {
// 如果正在初始化,等待初始化完成
if (this.initPromise) {
return this.initPromise;
}
// 创建初始化 Promise
this.initPromise = this.getGscRequestFn().then((instance) => {
this.requestInstance = instance;
this.initPromise = null;
return instance;
});
return this.initPromise;
}
throw new Error(
'[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法',
);
}
/**
* 检查 Request 是否已初始化
*/
isInitialized(): boolean {
return this.requestInstance !== null;
}
/**
* 销毁管理器
*/
destroy() {
this.requestInstance = null;
this.getGscRequestFn = null;
this.initPromise = null;
}
}
// 导出单例
export const gscRequestManager = new GscRequestManager();
/**
* GSC POST 请求封装(类似基座的 gscPost)
* @param url 请求地址
* @param data 请求数据
* @param config 请求配置
* @returns Promise<any> 响应数据
*/
export async function gscPost(
url: string,
data: any,
config: any = {},
): Promise<any> {
const request = await gscRequestManager.getRequest();
// Request 实例有 post 方法,但类型定义可能不完整,使用类型断言
return (request as any).post(url, data, config);
}
/**
* GSC GET 请求封装
* @param url 请求地址
* @param config 请求配置
* @returns Promise<any> 响应数据
*/
export async function gscGet(url: string, config: any = {}): Promise<any> {
const request = await gscRequestManager.getRequest();
// Request 实例有 get 方法,但类型定义可能不完整,使用类型断言
return (request as any).get(url, config);
}
/**
* 直接获取 Request 实例(高级用法)
* @returns Promise<Request> Request 实例
*/
export async function getGscRequest(): Promise<Request> {
return gscRequestManager.getRequest();
}
import GlOssApi from 'glsk-oss-jssdk';
/**
* 上传结果接口
*/
export interface UploadResult {
/** 阿里云地址 */
aliyunAddress: string;
/** 附件名称 */
attachment: string;
/** 其他可能的字段 */
[key: string]: any;
}
/**
* 上传配置选项
*/
export interface UploadOptions {
/** 上传进度回调 */
onProgress?: (progress: number) => void;
/** 上传成功回调 */
onSuccess?: (result: UploadResult) => void;
/** 上传失败回调 */
onError?: (error: Error) => void;
}
/**
* OSS 上传管理器
* 单例模式,统一管理文件上传
*/
class OssUploadManager {
private ossApi: GlOssApi | null = null;
/**
* 初始化 OSS API 实例
*/
private getOssApi(): GlOssApi {
if (!this.ossApi) {
this.ossApi = new GlOssApi();
}
return this.ossApi;
}
/**
* 上传文件
* @param file 要上传的文件
* @param options 上传配置选项
* @returns Promise<UploadResult> 上传结果
*/
async uploadFile(
file: File,
options: UploadOptions = {},
): Promise<UploadResult> {
if (!file) {
throw new Error('文件不能为空');
}
const ossApi = this.getOssApi();
return new Promise<UploadResult>((resolve, reject) => {
ossApi.multipartUpload(
file,
(result: UploadResult) => {
// 调用成功回调
options.onSuccess?.(result);
resolve(result);
},
(error: Error) => {
// 调用失败回调
options.onError?.(error);
reject(error);
},
);
});
}
/**
* 批量上传文件
* @param files 要上传的文件数组
* @param options 上传配置选项
* @returns Promise<UploadResult[]> 上传结果数组
*/
async uploadFiles(
files: File[],
options: UploadOptions = {},
): Promise<UploadResult[]> {
if (!files || files.length === 0) {
throw new Error('文件列表不能为空');
}
const uploadPromises = files.map((file) =>
this.uploadFile(file, options),
);
return Promise.all(uploadPromises);
}
}
// 导出单例实例
const ossUploadManager = new OssUploadManager();
/**
* 上传单个文件
* @param file 要上传的文件
* @param options 上传配置选项
* @returns Promise<UploadResult> 上传结果
*
* @example
* ```typescript
* const file = event.target.files[0];
* try {
* const result = await uploadFile(file, {
* onProgress: (progress) => console.log('上传进度:', progress),
* onSuccess: (result) => console.log('上传成功:', result.aliyunAddress),
* });
* console.log('文件地址:', result.aliyunAddress);
* } catch (error) {
* console.error('上传失败:', error);
* }
* ```
*/
export async function uploadFile(
file: File,
options: UploadOptions = {},
): Promise<UploadResult> {
return ossUploadManager.uploadFile(file, options);
}
/**
* 批量上传文件
* @param files 要上传的文件数组
* @param options 上传配置选项
* @returns Promise<UploadResult[]> 上传结果数组
*
* @example
* ```typescript
* const files = Array.from(event.target.files);
* try {
* const results = await uploadFiles(files);
* results.forEach(result => {
* console.log('文件地址:', result.aliyunAddress);
* });
* } catch (error) {
* console.error('上传失败:', error);
* }
* ```
*/
export async function uploadFiles(
files: File[],
options: UploadOptions = {},
): Promise<UploadResult[]> {
return ossUploadManager.uploadFiles(files, options);
}
/**
* 从文件输入元素上传文件
* @param fileInput HTML 文件输入元素或文件列表
* @param options 上传配置选项
* @returns Promise<UploadResult | UploadResult[]> 上传结果
*
* @example
* ```typescript
* const fileInput = document.getElementById('file') as HTMLInputElement;
* try {
* const result = await uploadFromInput(fileInput);
* console.log('文件地址:', result.aliyunAddress);
* } catch (error) {
* console.error('上传失败:', error);
* }
* ```
*/
export async function uploadFromInput(
fileInput: HTMLInputElement | FileList | File[],
options: UploadOptions = {},
): Promise<UploadResult | UploadResult[]> {
let files: File[] = [];
if (fileInput instanceof HTMLInputElement) {
if (!fileInput.files || fileInput.files.length === 0) {
throw new Error('请选择文件');
}
files = Array.from(fileInput.files);
} else if (fileInput instanceof FileList) {
files = Array.from(fileInput);
} else if (Array.isArray(fileInput)) {
files = fileInput;
} else {
throw new Error('不支持的文件输入类型');
}
if (files.length === 1) {
return uploadFile(files[0], options);
}
return uploadFiles(files, options);
}
......@@ -43,7 +43,6 @@ const getList = async () => {
pageSize: pagination.pageSize,
};
const res = await assistantList(requestData);
console.log('getList', res);
// 根据实际接口返回结构解析数据
let records = [];
let total = 0;
......
<script setup>
import { reactive, ref } from 'vue';
import {
ArrowDown,
Document,
EditPen,
Picture,
Upload,
VideoCamera,
View,
} from '@element-plus/icons-vue';
// --- 侧边栏数据 ---
const currentCategory = ref(1);
const totalMaterials = ref(60);
const categories = ref([
{ id: 1, name: '销售培训', count: 25 },
{ id: 2, name: '车型资料', count: 6 },
{ id: 3, name: '产品功能', count: 6 },
{ id: 4, name: '售后服务', count: 6 },
{ id: 5, name: '金融服务', count: 6 },
{ id: 6, name: '充电解决方案', count: 6 },
{ id: 7, name: '未分组', count: 5 },
]);
// --- 筛选数据 ---
const filterForm = reactive({
type: '',
name: '',
});
const handleSearch = () => {
console.log('Searching...', filterForm);
};
const handleReset = () => {
filterForm.type = '';
filterForm.name = '';
};
// --- 素材列表数据 ---
const selectedCount = ref(0);
const getTypeName = (type) => {
const map = { doc: '文档', image: '图片', video: '视频' };
return map[type];
};
// 核心:样式映射函数 - 用于处理不同类型的颜色主题
const getCardStyle = (type) => {
const styles = {
doc: {
cardBg: 'bg-[#f0f9f8]', // 极浅绿背景
iconBg: 'bg-[#d5eee6]', // 图标浅绿底
iconColor: 'text-[#4bb79d]', // 图标深绿
tagColor: 'text-[#4bb79d]', // 标签文字色
},
image: {
cardBg: 'bg-[#f2f4fc]', // 极浅紫背景
iconBg: 'bg-[#dbe4fd]',
iconColor: 'text-[#738cdd]',
tagColor: 'text-[#738cdd]',
},
video: {
cardBg: 'bg-[#f0f8ff]', // 极浅蓝背景
iconBg: 'bg-[#dcecff]',
iconColor: 'text-[#6eb0f7]',
tagColor: 'text-[#6eb0f7]',
},
};
return styles[type] || styles.doc;
};
// 模拟数据
const materials = ref([
{ id: 1, title: '2025年10月销售数据统计', type: 'doc' },
{ id: 2, title: '问界车型库', type: 'image' },
{ id: 3, title: '权益销售培训教程', type: 'video' },
{ id: 4, title: '权益销售培训教程', type: 'video' },
{ id: 5, title: '2025年第三季度销售部工作总结报告', type: 'doc' },
{ id: 6, title: '问界车型库', type: 'image' },
]);
// --- 分页数据 ---
const pagination = reactive({
currentPage: 1,
pageSize: 10,
});
</script>
<template>
<div
class="flex h-screen flex-col overflow-hidden bg-white font-sans text-gray-800"
>
<!-- 顶部标题栏 -->
<header class="flex-shrink-0 border-b border-gray-100 px-6 pt-5">
<h1 class="mb-5 text-lg font-semibold text-gray-800">知识管理</h1>
<div class="flex gap-8">
<div
class="cursor-pointer border-b-2 border-blue-500 pb-3 text-sm font-medium text-blue-500"
>
素材库
</div>
<div
class="cursor-pointer pb-3 text-sm text-gray-500 transition-colors hover:text-blue-500"
>
其他
</div>
</div>
</header>
<div class="flex flex-1 overflow-hidden bg-white p-6">
<!-- 左侧侧边栏 -->
<aside
class="mr-6 h-fit min-h-[600px] w-60 flex-shrink-0 rounded-lg border border-gray-200 py-4"
>
<div class="mb-3 px-5 text-sm font-medium text-gray-700">
全部素材 · {{ totalMaterials }}
</div>
<ul class="space-y-1">
<li
v-for="item in categories"
:key="item.id"
class="mx-2 flex h-10 cursor-pointer items-center justify-between rounded px-5 text-sm transition-colors duration-200"
:class="[
currentCategory === item.id
? 'bg-blue-50 text-blue-500'
: 'text-gray-600 hover:bg-gray-50',
]"
@click="currentCategory = item.id"
>
<span>{{ item.name }}</span>
<span
:class="
currentCategory === item.id
? 'text-blue-500'
: 'text-xs text-gray-400'
"
>
{{ item.count }}
</span>
</li>
</ul>
</aside>
<!-- 右侧内容区 -->
<main class="flex flex-1 flex-col overflow-hidden">
<!-- 筛选栏 -->
<div class="mb-5 flex flex-shrink-0 items-center justify-between">
<div class="flex items-center gap-6">
<div class="flex items-center gap-3">
<span class="whitespace-nowrap text-sm text-gray-600"
>文件类型</span
>
<el-select
v-model="filterForm.type"
placeholder="全部"
class="!w-[200px]"
>
<el-option label="全部" value="" />
<el-option label="文档" value="doc" />
<el-option label="图片" value="image" />
<el-option label="视频" value="video" />
</el-select>
</div>
<div class="flex items-center gap-3">
<span class="whitespace-nowrap text-sm text-gray-600"
>素材名称</span
>
<el-input
v-model="filterForm.name"
placeholder="请输入"
class="!w-[240px]"
/>
</div>
<div class="ml-3 flex gap-3">
<el-button type="primary" class="!px-6" @click="handleSearch">
查询
</el-button>
<el-button class="!px-6" @click="handleReset">重置</el-button>
</div>
</div>
</div>
<!-- 操作栏 -->
<div class="mb-5 flex flex-shrink-0 items-center justify-between">
<div class="text-sm text-gray-600">已选 {{ selectedCount }} 项</div>
<el-button type="primary">
<el-icon class="el-icon--left"><Upload /></el-icon>上传素材
</el-button>
</div>
<!-- 素材卡片列表 (Grid布局 + 滚动区) -->
<div class="flex-1 overflow-y-auto pr-2">
<div class="mb-6 grid grid-cols-3 gap-5">
<div
v-for="item in materials"
:key="item.id"
class="relative flex min-h-[140px] flex-col rounded-lg p-5 transition-shadow duration-300 hover:shadow-[0_4px_12px_rgba(0,0,0,0.05)]"
:class="getCardStyle(item.type).cardBg"
>
<!-- 卡片图标区域 -->
<div class="mb-4">
<div
class="flex h-12 w-12 items-center justify-center rounded-xl"
:class="[
getCardStyle(item.type).iconBg,
getCardStyle(item.type).iconColor,
]"
>
<el-icon v-if="item.type === 'doc'" :size="24">
<Document />
</el-icon>
<el-icon v-else-if="item.type === 'image'" :size="24">
<Picture />
</el-icon>
<el-icon v-else-if="item.type === 'video'" :size="24">
<VideoCamera />
</el-icon>
</div>
</div>
<!-- 卡片内容 -->
<div class="flex flex-1 flex-col">
<div
class="mb-2 line-clamp-2 h-[44px] text-base font-medium leading-snug text-gray-800"
>
{{ item.title }}
</div>
<!-- 标签 -->
<div
class="mb-6 self-start rounded bg-white px-2 py-0.5 text-xs"
:class="getCardStyle(item.type).tagColor"
>
{{ getTypeName(item.type) }}
</div>
<!-- 底部操作栏 -->
<div class="mt-auto flex items-center justify-between">
<div class="flex gap-4">
<button
class="flex items-center gap-1 text-[13px] text-blue-500 transition-colors hover:text-blue-600"
>
<el-icon><View /></el-icon> 预览
</button>
<button
class="flex items-center gap-1 text-[13px] text-blue-500 transition-colors hover:text-blue-600"
>
<el-icon><EditPen /></el-icon> 编辑
</button>
</div>
<el-dropdown trigger="click">
<span
class="flex cursor-pointer items-center gap-1 text-[13px] text-gray-600 transition-colors hover:text-blue-500"
>
更多 <el-icon><ArrowDown /></el-icon>
</span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item>下载</el-dropdown-item>
<el-dropdown-item class="!text-red-500">
删除
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div class="flex flex-shrink-0 items-center justify-end pt-5">
<div class="mr-4 text-sm text-gray-500">共 101 项数据</div>
<el-pagination
v-model:current-page="pagination.currentPage"
v-model:page-size="pagination.pageSize"
:page-sizes="[10, 20, 50]"
layout="sizes, prev, pager, next, jumper"
:total="101"
background
/>
</div>
</main>
</div>
</div>
</template>
<template>
<div class="app-container">
<!-- 触发按钮示例 -->
<!-- <el-button type="primary" @click="openDialog('create')">新建规则</el-button>
<el-button type="success" @click="openDialog('edit')">编辑规则 (带数据)</el-button> -->
<!-- 弹窗组件 -->
<el-dialog
v-model="dialogVisible"
:title="dialogTitle"
width="500px"
:close-on-click-modal="false"
@close="resetForm"
>
<el-form
ref="ruleFormRef"
:model="formData"
:rules="rules"
label-position="top"
class="rule-form"
>
<!-- 1. 规则/模版名称 -->
<el-form-item :label="screenTitle + '名称'" prop="name">
<el-input
v-model="formData.name"
:placeholder="'请输入' + screenTitle + '名称,支持中英文数字'"
maxlength="20"
show-word-limit
clearable
class="name-input"
/>
</el-form-item>
<!-- 2. 关联素材 (树形选择器) -->
<el-form-item
:label="screenType === 'rule' ? '关联素材' : '质检规则'"
prop="materials"
:required="screenType !== 'rule'"
>
<el-tree-select
v-model="formData.materials"
:data="treeData"
multiple
show-checkbox
node-key="id"
placeholder="请选择关联知识库的文件"
filterable
collapse-tags
collapse-tags-tooltip
:max-collapse-tags="1"
class="full-width "
/>
</el-form-item>
<!-- 3. 规则描述 -->
<el-form-item :label="screenType === 'rule' ? '规则描述' : '模版说明'" prop="description">
<el-input
v-model="formData.description"
type="textarea"
:placeholder="`请输入${screenType==='rule'?'规则详细描述':'模版说明'},支持中英文数字`"
maxlength="500"
show-word-limit
:rows="4"
resize="none"
/>
</el-form-item>
</el-form>
<!-- 底部按钮 -->
<template #footer>
<div class="dialog-footer">
<!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
<div class="w-[60px] h-[32px] mr-[8px] rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] text-[14px] hover:bg-[#ecf5ff] hover:text-[#1956fe] transition-all duration-200" @click="dialogVisible = false">取消</div>
<el-button type="primary" @click="submitForm">
{{ mode === 'create' ? '创建' + screenTitle : '保存' + screenTitle }}
</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, toRaw } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { inspectionRuleList, addInspectionRule as addInspectionRuleApi, addInspectionTemplate as addInspectionTemplateApi, updateInspectionRule as updateInspectionRuleApi, updateInspectionTemplate as updateInspectionTemplateApi } from '@/api/agentic'
import { findCategoryWithMaterialList } from '@/api/knowledge'
// 定义 emit
const emit = defineEmits<{
refresh: [type: 'rule' | 'template']
}>()
// --- 状态定义 ---
const dialogVisible = ref(false)
const mode = ref<'create' | 'edit'>('create')
const ruleFormRef = ref<FormInstance>()
const screenType = ref<string>('')
const screenTitle = ref<string>('')
// 动态标题
const dialogTitle = computed(() => (mode.value === 'create' ? '创建' + screenTitle.value : '编辑' + screenTitle.value))
// --- 表单数据 ---
const formData = reactive({
id: '',
name: '',
materials: [] as string[], // 存储选中的ID
description: '',
generalKnowledgeIds: [] as string[]
})
// --- 验证规则 ---
const rules = reactive<FormRules>({
name: [
{ required: true, message: '请输入规则名称', trigger: 'blur' }
],
description: [
{
required: true,
validator: (_rule, _value, callback) => {
if (!formData.description || formData.description.trim() === '') {
const message = screenType.value === 'template' ? '请输入模板说明' : '请输入规则详细描述'
callback(new Error(message))
} else {
callback()
}
},
trigger: 'blur'
}
],
materials: [
{
validator: (_rule, value, callback) => {
// 当 screenType !== 'rule' 时(即为模版时),materials 必传
if (screenType.value !== 'rule' && (!value || value.length === 0)) {
callback(new Error('请选择质检规则'))
} else {
callback()
}
},
trigger: ['change', 'blur']
}
]
})
// --- 树形数据 (对应截图右侧下拉框) ---
const treeData = ref([])
const addInspectionRule = async () => {
let requestData = {
"ruleName": formData.name,
"description": formData.description,
"materialIds": formData.materials
}
const res = await addInspectionRuleApi(requestData)
console.log("addInspectionRule",res)
ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
dialogVisible.value = false
// 通知父组件刷新规则列表
emit('refresh', 'rule')
}
const updateInspectionRule = async () => {
let requestData = {
"id": formData.id,
"ruleName": formData.name,
"description": formData.description,
"materialIds": formData.materials
}
const res = await updateInspectionRuleApi(requestData)
console.log("updateInspectionRule",res)
ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
dialogVisible.value = false
emit('refresh', 'rule')
}
const addInspectionTemplate = async () => {
let requestData = {
"templateName": formData.name,
"templateDescription": formData.description,
"ruleIds": formData.materials
}
const res = await addInspectionTemplateApi(requestData)
console.log(res)
ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
dialogVisible.value = false
// 通知父组件刷新模板列表
emit('refresh', 'template')
}
const updateInspectionTemplate = async () => {
let requestData = {
"id": formData.id,
"templateName": formData.name,
"templateDescription": formData.description,
"ruleIds": formData.materials
}
const res = await updateInspectionTemplateApi(requestData)
console.log("updateInspectionTemplate",res)
ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
dialogVisible.value = false
// 通知父组件刷新模板列表
emit('refresh', 'template')
}
const getCategoryWithMaterialList = async () => {
const res = await findCategoryWithMaterialList({})
const data = res || []
// 将 data 格式化为 treeData 结构
treeData.value = data.map((item: any) => ({
id: item.id,
label: item.name,
children: item.materials?.map((material: any) => ({
id: material.id,
label: material.name
})) || []
}))
console.log('格式化后的 treeData:', JSON.stringify(treeData.value))
}
const getInspectionRuleList = async () => {
const res = await inspectionRuleList({ id: formData.id })
console.log('inspectionRuleList:', res)
const data = res.records || []
// 将 data 格式化为 treeData 结构
treeData.value = data.map((item: any) => ({
id: item.id,
label: item.ruleName
}))
}
// --- 方法 ---
// 打开弹窗
const openDialog = async (type: 'create' | 'edit', screenTypeParam: string, row: any) => {
mode.value = type
dialogVisible.value = true
screenType.value = screenTypeParam
screenTitle.value = screenTypeParam === 'rule' ? '规则' : '模版';
console.log('row', row);
let editData = toRaw(row)
if(screenTypeParam === 'rule') {
await getCategoryWithMaterialList()
} else {
await getInspectionRuleList()
}
if (type === 'edit' && screenTypeParam ==='rule') {
formData.name = editData.ruleName
formData.id = editData.id
formData.materials = editData.materialIds
formData.description = editData.description
} else {
formData.name = editData.templateName
formData.id = editData.id
formData.materials = editData.ruleIds
formData.description = editData.templateDescription
}
}
// 重置表单 (关闭时触发)
const resetForm = () => {
if (!ruleFormRef.value) return
ruleFormRef.value.resetFields()
formData.materials = [] // resetFields有时无法清空非prop绑定的复杂对象,手动清空保险
}
// 提交表单
const submitForm = () => {
if (!ruleFormRef.value) return
ruleFormRef.value.validate((valid) => {
if (valid) {
if(screenType.value == 'rule') {
if(mode.value == 'create') {
addInspectionRule()
} else {
updateInspectionRule()
}
} else {
if(mode.value == 'create') {
addInspectionTemplate()
} else {
updateInspectionTemplate()
}
}
// 提交逻辑
// console.log('提交数据:', formData)
// ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
// dialogVisible.value = false
}
})
}
// 暴露方法给父组件使用
defineExpose({
openDialog
})
</script>
<style scoped>
.app-container {
padding: 20px;
}
/* 名称输入框宽度 */
.name-input {
width: 376px;
}
/* 让树形选择器宽度填满 */
.full-width {
width: 376px;
}
/* 调整 Dialog 底部按钮间距 */
.dialog-footer {
display: flex;
justify-content: flex-end;
}
</style>
<template>
<!-- 触发按钮示例 (实际使用时可删除) -->
<!-- <div class="demo-buttons">
<el-button type="primary" @click="openDialog('create')">新建培训计划</el-button>
<el-button type="success" @click="openDialog('edit')">编辑培训计划 (模拟回显)</el-button>
</div> -->
<!-- Dialog 弹窗组件 -->
<el-dialog
v-model="visible"
:title="dialogTitle"
width="600px"
:close-on-click-modal="false"
@closed="handleClose"
>
<el-form
ref="formRef"
:model="formData"
:rules="rules"
label-width="100px"
label-position="top"
class="training-form"
>
<!-- 1. 面向部门 -->
<el-form-item label="面向部门" prop="targetDeptId">
<el-cascader
v-model="formData.targetDeptId"
:options="departmentOptions"
placeholder="请选择部门"
clearable
class="w-[376px]"
@change="handleCascaderChange"
:props="{ value: 'departmentId', label: 'departmentName', children: 'children' }"
/>
</el-form-item>
<!-- 2. 学习内容 (核心:TreeSelect) -->
<el-form-item label="学习内容" prop="materialIds">
<el-tree-select
v-model="formData.materialIds"
:data="categoryList"
:render-after-expand="false"
show-checkbox
multiple
filterable
collapse-tags
collapse-tags-tooltip
placeholder="请选择学习内容"
style="width: 376px"
node-key="id"
/>
</el-form-item>
<!-- 3. 通用知识 (非必填) -->
<!-- <el-form-item label="通用知识" prop="generalKnowledge"> -->
<el-form-item label="通用知识" prop="generalIds">
<el-tree-select
v-model="formData.generalIds"
:data="treeData"
:render-after-expand="false"
show-checkbox
multiple
filterable
collapse-tags
collapse-tags-tooltip
placeholder="请选择学习内容"
style="width: 376px"
node-key="id"
/>
</el-form-item>
<!-- 4. 学习目标提示词 -->
<el-form-item label="学习目标提示词" prop="learningObjectivePrompt">
<el-input
v-model="formData.learningObjectivePrompt"
type="textarea"
:rows="4"
maxlength="5000"
show-word-limit
placeholder="例:创建一个15天的学习计划,需要学员了解产品核心卖点、典型案例分析,以及进行场景化小练习。请结合实际销售场景,设计渐进式的学习路径。"
/>
</el-form-item>
<!-- 5. 智能体主动联系 -->
<el-form-item label="学员无应答时,智能体是否主动联系" prop="proactiveContactEnabled">
<el-radio-group v-model="formData.proactiveContactEnabled" class="compact-radio-group">
<el-radio :label="true">是</el-radio>
<el-radio :label="false">否</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
<!-- 底部按钮 -->
<template #footer>
<div class="dialog-footer flex justify-end">
<!-- <el-button @click="visible = false">取 消</el-button> -->
<div class="w-[60px] h-[32px] mr-[8px] rounded-[5px] border border-[#E1E3E6] bg-white flex items-center justify-center cursor-pointer text-[#666666] text-[14px] hover:bg-[#ecf5ff] hover:text-[#1956fe] transition-all duration-200" @click="visible = false">取消</div>
<el-button type="primary" @click="submitForm" :loading="loading">
{{ mode === 'create' ? '创建计划' : '保存计划' }}
</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup>
import { ref, reactive, computed, onMounted, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { generalKnowledgeList, addTrainingPlan, updateTrainingPlan } from '@/api/agentic'
import { findDeptTree } from '@/api/dept'
import { findCategoryWithMaterialList } from '@/api/knowledge'
// 定义事件
const emit = defineEmits(['refresh'])
// --- 状态定义 ---
const visible = ref(false)
const mode = ref('create') // 'create' | 'edit'
const loading = ref(false)
const formRef = ref(null)
const departmentOptions = ref([])
const cascaderValue = ref([]);
// --- 表单数据 ---
const formData = reactive({
targetDeptId: '',
learningObjectivePrompt: '', // TreeSelect 绑定的通常是ID数组
materialIds: [],
generalIds: [],
proactiveContactEnabled: true
})
// --- 模拟树形数据 (对应图片右侧下拉框) ---
const treeData = ref([])
const categoryList = ref([])
// --- 校验规则 ---
const rules = {
targetDeptId: [{ required: true, message: '请选择面向部门', trigger: 'change' }],
materialIds: [{ required: true, message: '请选择学习内容', trigger: 'change' }],
generalIds: [{ required: true, message: '请选择通用知识', trigger: 'change' }],
learningObjectivePrompt: [{ required: true, message: '请输入学习目标提示词', trigger: 'blur' }],
proactiveContactEnabled: [{ required: true, message: '请选择是否主动联系', trigger: 'change' }]
}
// --- 计算属性 ---
const dialogTitle = computed(() => {
return mode.value === 'create' ? '创建培训计划' : '编辑培训计划'
})
const getDepartmentOptions = async () => {
const res = await findDeptTree({})
departmentOptions.value = res
}
const getCategoryList = async () => {
const res = await findCategoryWithMaterialList({})
console.log("getCategoryList",res);
categoryList.value = res.map((item) => ({
id: item.id,
label: item.name,
children: item.materials.map((child) => ({
id: child.id,
label: child.name
}))
}))
}
// --- 核心逻辑方法 ---
const getGeneralKnowledgeList = async () => {
const res = await generalKnowledgeList({})
treeData.value = res.map((item) => ({
id: item.id,
label: item.name,
children: item.materials.map((child) => ({
id: child.id,
label: child.name
}))
}))
}
/**
* 打开弹窗
* @param {String} type - 'create' 或 'edit'
* @param {Object} rowData - 编辑时传入的行数据
*/
const openDialog = async (type, rowData = null) => {
mode.value = type
visible.value = true
await getGeneralKnowledgeList()
await getDepartmentOptions()
await getCategoryList()
if (type === 'edit' && rowData) {
// 编辑模式:回显数据
const editData = toRaw(rowData)
console.log("editData",editData);
Object.assign(formData, {
id: editData.id || '',
targetDeptId: Number(editData.targetDeptId) || '',
materialIds: editData.materialIds || [],
generalIds: editData.generalIds || [],
learningObjectivePrompt: editData.learningObjectivePrompt || '',
proactiveContactEnabled: editData.proactiveContactEnabled !== undefined ? editData.proactiveContactEnabled : true
})
} else {
// 创建模式:重置表单
resetForm()
}
}
/**
* 初始化表单
* 重置表单数据和验证状态
*/
const resetForm = () => {
// 清除表单验证状态
if (formRef.value) {
formRef.value.resetFields()
formRef.value.clearValidate()
}
// 重置表单数据为默认值
Object.assign(formData, {
targetDeptId: '',
materialIds: [],
generalIds: [],
learningObjectivePrompt: '',
proactiveContactEnabled: true
})
// 重置级联选择器
cascaderValue.value = []
}
/**
* 关闭弹窗时的回调
* 用于重置表单,防止下次打开时有残留验证信息
*/
const handleClose = () => {
resetForm()
}
// 处理级联选择器变化
const handleCascaderChange = (value) => {
cascaderValue.value = value || [];
if (value && value.length > 0) {
formData.targetDeptId = value[value.length - 1];
} else {
formData.targetDeptId = 0;
}
// 触发校验
if (formRef.value) {
formRef.value.validateField('targetDeptId');
}
};
/**
* 提交表单
*/
const submitForm = async () => {
if (!formRef.value) return
await formRef.value.validate(async (valid) => {
if (valid) {
loading.value = true
try {
if(mode.value === 'create') {
await addTrainingPlan(formData)
} else {
await updateTrainingPlan(formData)
}
ElMessage.success(mode.value === 'create' ? '创建成功' : '保存成功')
visible.value = false
// 触发刷新事件,通知父组件刷新列表
emit('refresh')
} catch (error) {
console.error('提交失败:', error)
ElMessage.error(mode.value === 'create' ? '创建失败,请稍后重试' : '保存失败,请稍后重试')
} finally {
loading.value = false
// 调用完成后初始化表单
resetForm()
}
} else {
console.log('表单校验失败')
return false
}
})
}
// 暴露方法给父组件使用
defineExpose({
openDialog
})
</script>
<style scoped>
.demo-buttons {
padding: 20px;
}
/* 调整表单项的间距,使其更像设计图 */
.training-form .el-form-item {
margin-bottom: 24px;
}
/* 强制让Label字体加粗一点,更像标题 */
:deep(.el-form-item__label) {
font-weight: 500;
color: #303133;
}
/* 优化 radio 组件样式,选中后文字颜色保持不变 */
:deep(.el-radio) {
color: #606266;
}
:deep(.el-radio.is-checked .el-radio__label) {
color: #606266 !important;
}
:deep(.el-radio__input.is-checked + .el-radio__label) {
color: #606266 !important;
}
/* 缩小 radio-group 中 radio 之间的间距 */
:deep(.compact-radio-group .el-radio) {
margin-right: 24px;
}
</style>
<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import {
ChatDotRound,
Cpu,
DataAnalysis,
Monitor,
Notebook,
Reading,
TrendCharts,
UserFilled,
} from '@element-plus/icons-vue';
import AgenticQuality from './components/AgenticQuality.vue';
import AgenticPractice from './components/AgenticPractice.vue';
import AgenticReplay from './components/AgenticReplay.vue';
import AgenticTrain from './components/AgenticTrain.vue';
// 状态
const activeMenu = ref(0);
// 容器引用
const scrollContainerRef = ref(null);
// 滚动数据
const scrollData = ref({
scrollTop: 0,
scrollLeft: 0,
scrollHeight: 0,
clientHeight: 0,
scrollWidth: 0,
clientWidth: 0,
});
// 处理滚动事件
const handleScroll = (event) => {
const target = event?.target || event?.currentTarget || scrollContainerRef.value;
if (!target) return;
scrollData.value = {
scrollTop: target.scrollTop,
scrollLeft: target.scrollLeft,
scrollHeight: target.scrollHeight,
clientHeight: target.clientHeight,
scrollWidth: target.scrollWidth,
clientWidth: target.clientWidth,
};
// 调试信息,可以在控制台查看滚动数据
console.log('滚动事件触发:', {
scrollTop: scrollData.value.scrollTop,
scrollHeight: scrollData.value.scrollHeight,
clientHeight: scrollData.value.clientHeight,
});
};
// 初始化滚动监听
const initScrollListener = async () => {
await nextTick();
if (scrollContainerRef.value) {
// 先移除旧的监听器(如果存在)
scrollContainerRef.value.removeEventListener('scroll', handleScroll);
// 添加新的监听器
scrollContainerRef.value.addEventListener('scroll', handleScroll, { passive: true });
console.log('滚动监听器已绑定');
} else {
console.warn('滚动容器引用未找到');
}
};
// 组件挂载后添加事件监听
onMounted(() => {
initScrollListener();
});
// 监听 activeMenu 变化,当切换组件时重新初始化监听
watch(activeMenu, () => {
initScrollListener();
});
// 菜单点击切换时重置滚动条
const handleMenuClick = async (index) => {
activeMenu.value = index;
// 等待组件内容渲染完毕
await nextTick();
// 再通过 requestAnimationFrame 确保 DOM 布局完成后再滚动
requestAnimationFrame(() => {
const el = scrollContainerRef.value;
if (!el) return;
el.scrollTo({ top: 0, left: 0, behavior: 'auto' });
// 更新一次滚动数据,保持同步
handleScroll({ target: el });
});
};
// 组件卸载前移除事件监听
onUnmounted(() => {
if (scrollContainerRef.value) {
scrollContainerRef.value.removeEventListener('scroll', handleScroll);
}
});
// 数据源:侧边栏
const sidebarItems = [
{
icon: Monitor,
title: '质检智能体',
desc: '对话质量检测和评估',
color: 'bg-blue-500',
activeColor: 'bg-blue-500',
},
{
icon: ChatDotRound,
title: '对练智能体',
desc: '销售和客服对话训练',
color: 'bg-[#2ccdce]',
activeColor: 'bg-[#2ccdce]',
},
{
icon: TrendCharts,
title: '复盘智能体',
desc: '对话过程分析和总结',
color: 'bg-orange-400',
activeColor: 'bg-orange-400',
},
{
icon: Reading,
title: '培训智能体',
desc: '员工产品知识培训',
color: 'bg-indigo-500',
activeColor: 'bg-indigo-500',
},
];
</script>
<template>
<div class="w-full bg-white text-[#1d2129]">
<header class="w-full h-[60px] bg-white sticky top-0 z-50">
<div class="p-6">
<h1 class="text-lg font-bold tracking-wide text-gray-900 pl-[4px]">
智能体管理
</h1>
</div>
</header>
<!-- 主要内容 -->
<main class="flex">
<aside
class="sticky top-[60px] self-start flex h-[760px] w-[278px] flex-shrink-0 flex-col bg-white ml-[24px] rounded-[12px] border border-[#E1E3E6]"
>
<div class="w-[278px] h-47 flex-1 space-y-2 overflow-y-auto px-4 ">
<div class="mr-[16px] mt-[16px] mb-[16px] text-[14px] text-[#2F3133] font-normal">智能体列表</div>
<div
v-for="(item, index) in sidebarItems"
:key="index"
@click="handleMenuClick(index)"
class="group flex cursor-pointer items-center rounded-[8px] p-4 transition-all duration-200"
:class="activeMenu === index ? 'bg-[#eef6ff]' : 'hover:bg-gray-50'"
>
<!-- 图标容器 -->
<div
class="mr-4"
>
<img v-if="index === 0" src="/images/icon-agentic-quality.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" />
<img v-if="index === 1" src="/images/icon-agentic-practice.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" />
<img v-if="index === 2" src="/images/icon-agentic-replay.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" />
<img v-if="index === 3" src="/images/icon-agentic-train.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" />
</div>
<!-- 文本 -->
<div class="flex flex-col">
<span
class="mb-0.5 text-base font-medium text-[#2F3133]"
>
{{ item.title }}
</span>
<span class="text-[12px] text-[#969AA3]">{{
item.desc
}}</span>
</div>
</div>
</div>
</aside>
<!-- 右侧主要内容区 -->
<section
ref="scrollContainerRef"
class="flex-1 overflow-y-auto scroll-smooth bg-white pr-[24px] pb-[94px]"
:style="{ height: 'calc(100vh - 60px)' }"
@scroll="handleScroll"
>
<AgenticQuality v-if="activeMenu === 0" />
<AgenticPractice v-if="activeMenu === 1" />
<AgenticReplay v-if="activeMenu === 2" />
<AgenticTrain v-if="activeMenu === 3" />
</section>
</main>
</div>
</template>
<style>
/* 隐藏默认滚动条但保持可滚动,提升美观度 (可选) */
main::-webkit-scrollbar {
width: 6px;
}
main::-webkit-scrollbar-track {
background: transparent;
}
main::-webkit-scrollbar-thumb {
background-color: #e5e7eb;
border-radius: 20px;
}
</style>
<template>
<div class="notfound-view">
<div class="content-card">
<div class="error-code">
404
</div>
<h1>页面未找到</h1>
<p>抱歉,您访问的页面不存在或已被删除</p>
<button class="btn-home" @click="goHome">
🏠 返回首页
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push("/");
router.push('/');
};
</script>
<template>
<div class="notfound-view">
<div class="content-card">
<div class="error-code">404</div>
<h1>页面未找到</h1>
<p>抱歉,您访问的页面不存在或已被删除</p>
<button @click="goHome" class="btn-home">🏠 返回首页</button>
</div>
</div>
</template>
<style scoped>
.notfound-view {
display: flex;
align-items: center;
justify-content: center;
max-width: 600px;
min-height: 400px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
max-width: 600px;
min-height: 400px;
margin: 0 auto;
}
.content-card {
padding: 3rem;
text-align: center;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
padding: 3rem;
text-align: center;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.error-code {
margin-bottom: 1rem;
font-size: 6rem;
font-weight: 700;
background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%));
background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 1rem;
font-size: 6rem;
font-weight: 700;
background: linear-gradient(45deg, #fff, rgb(255 255 255 / 60%));
background-clip: text;
-webkit-text-fill-color: transparent;
}
.content-card h1 {
margin: 0 0 1rem;
font-size: 2rem;
margin: 0 0 1rem;
font-size: 2rem;
}
.content-card p {
margin: 0 0 2rem;
opacity: 0.9;
margin: 0 0 2rem;
opacity: 0.9;
}
.btn-home {
padding: 0.75rem 2rem;
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
padding: 0.75rem 2rem;
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-home:hover {
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
</style>
<template>
<div class="user-view">
<div class="content-card">
<h1>👥 用户管理</h1>
<div class="toolbar">
<button class="btn-add" @click="addUser">
➕ 新增用户
</button>
</div>
<div class="table-container">
<table class="user-table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<span class="badge" :class="`badge-${user.role}`">
{{ user.role }}
</span>
</td>
<td>
<span class="status" :class="user.active ? 'status-active' : 'status-inactive'">
{{ user.active ? "在线" : "离线" }}
</span>
</td>
<td>
<button class="btn-edit" @click="editUser(user)">
编辑
</button>
<button class="btn-delete" @click="deleteUser(user.id)">
删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ref } from 'vue';
interface User {
active: boolean;
email: string;
id: number;
name: string;
role: "admin" | "guest" | "user";
active: boolean;
email: string;
id: number;
name: string;
role: 'admin' | 'guest' | 'user';
}
const users = ref<User[]>([
{
id: 1,
name: "张三",
email: "zhangsan@example.com",
role: "admin",
active: true,
},
{
id: 2,
name: "李四",
email: "lisi@example.com",
role: "user",
active: true,
},
{
id: 3,
name: "王五",
email: "wangwu@example.com",
role: "user",
active: false,
},
{
id: 4,
name: "赵六",
email: "zhaoliu@example.com",
role: "guest",
active: true,
},
{
id: 1,
name: '张三',
email: 'zhangsan@example.com',
role: 'admin',
active: true,
},
{
id: 2,
name: '李四',
email: 'lisi@example.com',
role: 'user',
active: true,
},
{
id: 3,
name: '王五',
email: 'wangwu@example.com',
role: 'user',
active: false,
},
{
id: 4,
name: '赵六',
email: 'zhaoliu@example.com',
role: 'guest',
active: true,
},
]);
const addUser = () => {
const newUser: User = {
id: users.value.length + 1,
name: `新用户${users.value.length + 1}`,
email: `user${users.value.length + 1}@example.com`,
role: "user",
active: true,
};
users.value.push(newUser);
const newUser: User = {
id: users.value.length + 1,
name: `新用户${users.value.length + 1}`,
email: `user${users.value.length + 1}@example.com`,
role: 'user',
active: true,
};
users.value.push(newUser);
};
const editUser = (user: User) => {
console.log("编辑用户:", user);
console.log('编辑用户:', user);
alert(`编辑用户: ${user.name}`);
};
const deleteUser = (id: number) => {
const index = users.value.findIndex((u) => u.id === id);
// eslint-disable-next-line
if (index !== -1 && confirm(`确定要删除用户 ${users.value[index].name} 吗?`)) {
users.value.splice(index, 1);
}
const index = users.value.findIndex((u) => u.id === id);
if (
index !== -1 &&
confirm(`确定要删除用户 ${users.value[index].name} 吗?`)
) {
users.value.splice(index, 1);
}
};
</script>
<template>
<div class="user-view">
<div class="content-card">
<h1>👥 用户管理</h1>
<div class="toolbar">
<button @click="addUser" class="btn-add">➕ 新增用户</button>
</div>
<div class="table-container">
<table class="user-table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<span class="badge" :class="`badge-${user.role}`">
{{ user.role }}
</span>
</td>
<td>
<span
class="status"
:class="user.active ? 'status-active' : 'status-inactive'"
>
{{ user.active ? '在线' : '离线' }}
</span>
</td>
<td>
<button @click="editUser(user)" class="btn-edit">编辑</button>
<button @click="deleteUser(user.id)" class="btn-delete">
删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<style scoped>
.user-view {
max-width: 1200px;
margin: 0 auto;
max-width: 1200px;
margin: 0 auto;
}
.content-card {
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 1.5rem;
font-size: 2rem;
margin: 0 0 1.5rem;
font-size: 2rem;
}
.toolbar {
margin-bottom: 1.5rem;
margin-bottom: 1.5rem;
}
.btn-add {
padding: 0.75rem 1.5rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
padding: 0.75rem 1.5rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(76 175 80 / 80%);
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-add:hover {
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
.table-container {
overflow-x: auto;
overflow-x: auto;
}
.user-table {
width: 100%;
border-collapse: collapse;
width: 100%;
border-collapse: collapse;
}
.user-table thead {
background: rgb(255 255 255 / 10%);
background: rgb(255 255 255 / 10%);
}
.user-table th,
.user-table td {
padding: 1rem;
text-align: left;
border-bottom: 1px solid rgb(255 255 255 / 10%);
padding: 1rem;
text-align: left;
border-bottom: 1px solid rgb(255 255 255 / 10%);
}
.user-table th {
font-weight: 600;
color: rgb(255 255 255 / 95%);
font-weight: 600;
color: rgb(255 255 255 / 95%);
}
.user-table tbody tr {
transition: background 0.3s ease;
transition: background 0.3s ease;
}
.user-table tbody tr:hover {
background: rgb(255 255 255 / 5%);
background: rgb(255 255 255 / 5%);
}
.badge {
padding: 0.25rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
padding: 0.25rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
}
.badge-admin {
background: rgb(244 67 54 / 80%);
background: rgb(244 67 54 / 80%);
}
.badge-user {
background: rgb(33 150 243 / 80%);
background: rgb(33 150 243 / 80%);
}
.badge-guest {
background: rgb(158 158 158 / 80%);
background: rgb(158 158 158 / 80%);
}
.status {
padding: 0.25rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
padding: 0.25rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
border-radius: 1rem;
}
.status-active {
background: rgb(76 175 80 / 80%);
background: rgb(76 175 80 / 80%);
}
.status-inactive {
background: rgb(158 158 158 / 80%);
background: rgb(158 158 158 / 80%);
}
.btn-edit,
.btn-delete {
padding: 0.5rem 1rem;
margin-right: 0.5rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
padding: 0.5rem 1rem;
margin-right: 0.5rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-edit {
color: white;
background: rgb(33 150 243 / 80%);
color: white;
background: rgb(33 150 243 / 80%);
}
.btn-edit:hover {
background: rgb(33 150 243 / 100%);
background: rgb(33 150 243 / 100%);
}
.btn-delete {
color: white;
background: rgb(244 67 54 / 80%);
color: white;
background: rgb(244 67 54 / 80%);
}
.btn-delete:hover {
background: rgb(244 67 54 / 100%);
background: rgb(244 67 54 / 100%);
}
</style>
export { default } from '@venus/tailwind-config';
{
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
/* Path Alias */
"baseUrl": ".",
"module": "ESNext",
/* Path Alias */
"baseUrl": ".",
"module": "ESNext",
/* Bundler mode */
"moduleResolution": "bundler",
"paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
/* Bundler mode */
"moduleResolution": "bundler",
"paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
"allowJs": true,
/* Linting */
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"references": [{ "path": "./tsconfig.node.json" }],
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
/* Linting */
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"references": [{ "path": "./tsconfig.node.json" }],
"include": [
"env.d.ts",
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.js"
]
}
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
}

VITE_APP_NAME=venus-base
VITE_APP_NAME=venus-agentic-base
VITE_APP_VERSION=1.0.0
VITE_PORT=8080
VITE_API_BASE_URL=http://localhost:3000/api
VITE_API_BASE_URL=http://192.168.1.125:9898/
VITE_API_TIMEOUT=30000
VITE_SUBAPP_VUE_ENTRY=http://localhost:8081
......@@ -12,7 +12,7 @@ VITE_SUBAPP_REACT_ENTRY=http://localhost:8082
VITE_BASE_URL=/
VITE_USE_MOCK=true
VITE_USE_MOCK=false
VITE_DEBUG=true
......
......@@ -73,16 +73,16 @@ pnpm preview
```typescript
export const microApps: MicroAppConfig[] = [
{
name: "subapp-vue", // 微应用名称
entry: "//localhost:8081", // 微应用入口
container: "#subapp-container", // 微应用挂载点
activeRule: "/subapp-vue", // 激活路由
props: {
routerBase: "/subapp-vue", // 路由基础路径
},
},
// 添加更多微应用...
{
name: 'subapp-vue', // 微应用名称
entry: '//localhost:8081', // 微应用入口
container: '#subapp-container', // 微应用挂载点
activeRule: '/subapp-vue', // 激活路由
props: {
routerBase: '/subapp-vue', // 路由基础路径
},
},
// 添加更多微应用...
];
```
......@@ -104,10 +104,10 @@ export const microApps: MicroAppConfig[] = [
- **顶部导航栏**: 包含 Logo、主菜单和用户信息
- **侧边栏**: 可折叠的侧边导航菜单
- **内容区域**:
- 面包屑导航
- 页面内容容器
- 微应用挂载容器(`#subapp-container`)
- **内容区域**:
- 面包屑导航
- 页面内容容器
- 微应用挂载容器(`#subapp-container`)
- **底部**: 版权信息
## qiankun 配置
......@@ -115,24 +115,24 @@ export const microApps: MicroAppConfig[] = [
主应用在 `main.ts` 中初始化 qiankun:
```typescript
import { registerMicroApps, start } from "qiankun";
import { registerMicroApps, start } from 'qiankun';
// 注册微应用
registerMicroApps(microApps, {
beforeLoad: (app) => console.log("before load", app.name),
beforeMount: (app) => console.log("before mount", app.name),
afterMount: (app) => console.log("after mount", app.name),
beforeUnmount: (app) => console.log("before unmount", app.name),
afterUnmount: (app) => console.log("after unmount", app.name),
beforeLoad: (app) => console.log('before load', app.name),
beforeMount: (app) => console.log('before mount', app.name),
afterMount: (app) => console.log('after mount', app.name),
beforeUnmount: (app) => console.log('before unmount', app.name),
afterUnmount: (app) => console.log('after unmount', app.name),
});
// 启动 qiankun
start({
prefetch: true, // 预加载
sandbox: {
strictStyleIsolation: false,
experimentalStyleIsolation: true,
},
prefetch: true, // 预加载
sandbox: {
strictStyleIsolation: false,
experimentalStyleIsolation: true,
},
});
```
......@@ -151,17 +151,17 @@ start({
let instance: any = null;
export async function bootstrap() {
console.log("vue app bootstraped");
console.log('vue app bootstraped');
}
export async function mount(props: any) {
instance = createApp(App);
instance.mount(props.container ? props.container.querySelector("#app") : "#app");
instance = createApp(App);
instance.mount(props.container ? props.container.querySelector('#app') : '#app');
}
export async function unmount() {
instance.unmount();
instance = null;
instance.unmount();
instance = null;
}
```
......@@ -169,20 +169,20 @@ export async function unmount() {
```typescript
// vite.config.ts
import qiankun from "vite-plugin-qiankun";
import qiankun from 'vite-plugin-qiankun';
export default defineConfig({
plugins: [
vue(),
qiankun("subapp-vue", {
useDevMode: true,
}),
],
server: {
port: 8081,
cors: true,
origin: "http://localhost:8081",
},
plugins: [
vue(),
qiankun('subapp-vue', {
useDevMode: true
})
],
server: {
port: 8081,
cors: true,
origin: 'http://localhost:8081'
}
});
```
......@@ -223,3 +223,4 @@ export default defineConfig({
## License
MIT
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!