Commit aba1cf3b by 林磊

Merge branch 'dev_linlei' into 'dev'

Dev dev_linlei Merge Request dev

See merge request !8
2 parents 696da18b 1b9120f1
Showing 125 changed files with 1242 additions and 3480 deletions
---
"@venus/docs": major
---
编写变更说明:修改说明文档中相关技术说明
......@@ -110,7 +110,7 @@
"**/bower_components": true,
"**/.turbo": true,
"**/.idea": true,
"**/.vitepress": true,
"**/.vitepress": false,
"**/tmp": true,
"**/.git": true,
"**/.svn": true,
......@@ -118,7 +118,7 @@
"**/CVS": true,
"**/.stylelintcache": true,
"**/.DS_Store": true,
"**/vite.config.mts.*": true,
"**/vite.config.mts.*": false,
"**/tea.yaml": true
},
"files.watcherExclude": {
......
{
"name": "@venus/venus-agentic-assisant",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"description": "汽车智能体-智能助理",
"private": true,
"type": "module",
"scripts": {
......@@ -12,25 +12,26 @@
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vue-office/docx": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/excel": "catalog:",
"@element-plus/icons-vue": "catalog:",
"@js-preview/docx": "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:*",
"@venus/tailwind-config": "workspace:*",
"@venus/tools": "workspace:*",
"@vue-office/docx": "catalog:",
"@vue-office/excel": "catalog:",
"@vue-office/pdf": "catalog:",
"@vue-office/pptx": "catalog:",
"@vueuse/core": "catalog:",
"axios": "catalog:",
"element-plus": "catalog:",
"glsk-oss-jssdk": "catalog:",
"pinia": "catalog:",
"sass": "catalog:",
"tailwindcss": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:",
"glsk-oss-jssdk": "catalog:",
"sass": "catalog:"
"vue-router": "catalog:"
},
"devDependencies": {
......
<script setup lang="ts">
import { onMounted } from 'vue';
import { onMounted } from "vue";
onMounted(() => {
// console.log('Vue3 微应用已挂载');
// 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>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition mode="out-in" name="fade">
<component :is="Component" />
</transition>
</router-view>
</main>
</template>
<style scoped>
......
......@@ -9,6 +9,7 @@ import {
qiankunWindow,
renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';
import CommonUI from '@venus/common-ui-vue';
import App from './App.vue';
import { createRouter } from './router';
......@@ -28,6 +29,9 @@ async function render(props: QiankunProps = {}) {
app = createApp(App);
// 注册通用 UI 组件库
app.use(CommonUI);
// 配置 Pinia
app.use(createPinia());
......
// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: 2026/1/22 14:14:23
import type { RouteRecordRaw } from 'vue-router';
export const autoRoutes: RouteRecordRaw[] = [
{
path: "/assistant/index",
id: "assistant",
title: "Assistant",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "assistant",
"keepAlive": false,
"requiresAuth": false,
"title": "Assistant"
},
children: [
{
path: "add-update",
id: "assistant-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "assistant:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/manage-agentic/index",
id: "manage-agentic",
title: "ManageAgentic",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "manage-agentic",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageAgentic"
},
},
{
path: "/manage-konw/index",
id: "manage-konw",
title: "ManageKonw",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "manage-konw",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageKonw"
},
children: [
{
path: "add-update",
id: "manage-konw-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "manage-konw:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/communication",
id: ".-communication",
title: "Communication",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "communication",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Communication"
},
},
{
path: "/home",
id: ".-home",
title: "Home",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "home",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Home"
},
},
{
path: "/settings",
id: ".-settings",
title: "Settings",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "settings",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Settings"
},
},
{
path: "/user",
id: ".-user",
title: "User",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "user",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "User"
},
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/NotFound.vue"),
meta: {
"title": "404",
"hidden": true
},
}
];
......@@ -2,84 +2,124 @@ 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: '首页',
// 导入自动生成的路由
// 注意:使用动态导入以避免构建时错误
let autoRoutes: RouteRecordRaw[] = [];
// 使用同步方式导入(在构建时生成的文件)
// 由于项目使用 ES 模块,这里使用条件导入
try {
// @ts-ignore - 动态导入可能不存在,使用同步导入
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const autoRoutesModule = require('./auto-routes');
autoRoutes = autoRoutesModule.autoRoutes || [];
} catch (error) {
// 如果自动生成的路由文件不存在,使用手动配置的路由
console.warn('[router] 自动路由文件不存在,使用手动配置的路由');
// 手动配置的路由(作为后备方案)
autoRoutes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: '首页',
},
},
},
{
path: '/managekonw',
name: 'ManageKonw',
component: () => import('@/views/ManageKonw/index.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: '/assistant',
name: 'Assistant',
component: () => import('@/views/Assistant/index.vue'),
meta: {
title: '岗位助理配置',
},
},
},
{
path: '/manageagentic',
name: 'ManageAgentic',
component: () => import('@/views/ManageAgentic/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/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: '/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: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: '用户管理',
},
},
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.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: '/communication',
name: 'Communication',
component: () => import('@/views/Communication.vue'),
meta: {
title: '通信示例',
},
},
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
},
];
}
// 手动配置的路由(用于覆盖或补充自动生成的路由)
// 手动配置的路由优先级更高,会覆盖自动生成的路由
const manualRoutes: RouteRecordRaw[] = [
// 可以在这里添加需要手动配置的特殊路由
// 例如:需要特殊权限、动态参数等的路由
// {
// path: '/custom',
// name: 'Custom',
// component: () => import('@/views/Custom.vue'),
// meta: {
// title: '自定义路由',
// },
// },
];
// 合并路由:手动配置的路由优先
const routes: RouteRecordRaw[] = [
...manualRoutes,
...autoRoutes.filter(
(autoRoute) => !manualRoutes.some((manualRoute) => manualRoute.path === autoRoute.path)
),
];
/**
......
/**
* 路由类型扩展
* 扩展 Vue Router 的 RouteRecordRaw 接口,支持自定义字段
*/
import 'vue-router';
declare module 'vue-router' {
interface RouteRecordRaw {
/** 路由唯一标识 */
id?: string;
/** 路由标题 */
title?: string;
/** 路由图标 */
icon?: string;
/** 路由层级 */
level?: number;
/** 是否隐藏路由 */
hidden?: boolean;
/** 允许其他自定义属性 */
[key: string]: unknown;
}
}
......@@ -3,8 +3,11 @@
"composite": true,
"module": "ESNext",
"moduleResolution": "bundler",
"paths": {
"@venus/tools/*": ["../../../../packages/tools/src/*"]
},
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "vite-plugins/**/*.ts"]
}
import type { Plugin } from 'vite';
import type { Plugin } from "vite";
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
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';
// @ts-ignore - workspace package, resolved by resolveWorkspacePackage plugin
import { autoRoutes } from "@venus/tools/src/vite-plugins/auto-routes";
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 __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PORT = 8081;
const APP_NAME = 'assisant'; // 与基座配置的 name 一致
// 获取源码路径
const commonUiSourcePath = resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
const APP_NAME = "assisant"; // 与基座配置的 name 一致
const toolsSourcePath = resolve(
__dirname,
"../../../../packages/tools/src",
);
// 自定义插件:强制解析 @venus/common-ui-vue
// 自定义插件:强制解析 @venus/tools workspace 包
function resolveWorkspacePackage(): Plugin {
return {
name: 'resolve-workspace-package',
enforce: 'pre', // 在其他插件之前执行
resolveId(id, importer) {
// 精确匹配包名
if (
id === '@venus/common-ui-vue' ||
id.startsWith('@venus/common-ui-vue/')
) {
// 验证文件是否存在
if (existsSync(commonUiSourcePath)) {
return {
id: commonUiSourcePath,
external: false,
};
}
console.warn(
`[resolve-workspace-package] 文件不存在: ${commonUiSourcePath}`,
);
}
return null;
},
};
return {
name: "resolve-workspace-package",
enforce: "pre", // 在其他插件之前执行
resolveId(id, importer) {
// 解析 @venus/tools
if (id.startsWith("@venus/tools/")) {
const subPath = id.replace("@venus/tools/", "");
// 处理相对路径导入(如 ../utils/route-generator)
let resolvedPath = resolve(toolsSourcePath, subPath);
// 如果是目录,尝试查找 index 文件
if (!resolvedPath.endsWith(".ts") && !resolvedPath.endsWith(".js")) {
// 尝试添加 .ts 扩展名
const resolvedPathWithExt = `${resolvedPath}.ts`;
if (existsSync(resolvedPathWithExt)) {
resolvedPath = resolvedPathWithExt;
} else {
// 尝试作为目录查找 index.ts
const indexPath = resolve(resolvedPath, "index.ts");
if (existsSync(indexPath)) {
resolvedPath = indexPath;
}
}
}
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
}
// 处理包内部的相对路径导入(如 ../utils/route-generator.js)
// TypeScript 中使用 .js 扩展名导入 .ts 文件是标准做法
if (importer && importer.includes("packages/tools/src") && (id.startsWith("../") || id.startsWith("./"))) {
const importerDir = dirname(importer);
const resolvedPath = resolve(importerDir, id);
// 如果已经有扩展名
if (resolvedPath.endsWith(".js")) {
// TypeScript 使用 .js 扩展名导入 .ts 文件,需要替换为 .ts
const tsPath = resolvedPath.replace(/\.js$/, ".ts");
if (existsSync(tsPath)) {
return {
id: tsPath,
external: false,
};
}
// 如果 .ts 不存在,尝试使用 .js
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
} else if (resolvedPath.endsWith(".ts")) {
// 直接使用 .ts 扩展名
if (existsSync(resolvedPath)) {
return {
id: resolvedPath,
external: false,
};
}
} else {
// 没有扩展名,尝试添加 .ts(优先)或 .js
const resolvedPathWithTs = `${resolvedPath}.ts`;
if (existsSync(resolvedPathWithTs)) {
return {
id: resolvedPathWithTs,
external: false,
};
}
const resolvedPathWithJs = `${resolvedPath}.js`;
if (existsSync(resolvedPathWithJs)) {
return {
id: resolvedPathWithJs,
external: false,
};
}
}
}
return null;
},
};
}
export default defineConfig(({ mode, command }) => {
const isDev = mode === 'development';
const isServe = command === 'serve';
// 生产环境使用 /child/ 前缀,确保所有资源路径都带上该前缀
const basePath = isDev && isServe ? `http://localhost:${PORT}/` : `/child/${APP_NAME}/`;
const isDev = mode === "development";
const isServe = command === "serve";
// 生产环境使用 /child/ 前缀,确保所有资源路径都带上该前缀
const basePath = isDev && isServe ? `http://localhost:${PORT}/` : `/child/${APP_NAME}/`;
return {
base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径
plugins: [
resolveWorkspacePackage(),
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: [
{
find: '@',
replacement: resolve(__dirname, 'src'),
},
{
find: '@public',
replacement: resolve(__dirname, 'public'),
},
{
find: '@venus/common-ui-vue',
replacement: resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
),
},
],
// 设置条件导出优先使用 development
conditions: ['development', 'module', 'import', 'default'],
},
// 优化依赖预构建,排除 workspace 包
optimizeDeps: {
exclude: ['@venus/common-ui-vue', 'jiti'],
include: [],
},
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 不拆分
assetsDir: 'assets', // 资源文件目录
rollupOptions: {
output: {
// qiankun 需要的输出格式
format: 'umd',
// UMD 库名称,必须与应用名称一致
name: `qiankunApp_${APP_NAME.replace(/-/g, '_')}`,
// 资源文件路径配置,Vite 会自动将 base 路径(/child/${APP_NAME}/)应用到这些路径
entryFileNames: 'assets/[name].js',
chunkFileNames: 'assets/[name].[hash].js',
assetFileNames: 'assets/[name].[hash].[ext]',
// 内联所有动态导入,解决顶层 await 问题
inlineDynamicImports: true,
},
},
},
};
return {
base: basePath, // 生产环境使用 /child/ 前缀作为基础路径,Vite 会自动应用到所有资源路径
plugins: [
resolveWorkspacePackage(),
// 自动路由生成插件(需要在其他插件之前执行)
autoRoutes({
viewsDir: "src/views",
outputFile: "src/router/auto-routes.ts",
routePrefix: "",
exclude: [ "components", "components/", "NotFound.vue" ],
watch: isDev, // 开发模式下监听文件变化
// 自定义路由规则示例
customRules: (filePath, routeConfig) => {
return routeConfig;
},
}),
vue(),
vueJsx(),
// 自动导入 Vue 相关函数
AutoImport({
imports: [ "vue", "vue-router", "pinia" ],
dts: "src/auto-imports.d.ts",
eslintrc: {
enabled: false,
},
}),
// 自动导入组件
Components({
dts: "src/components.d.ts",
}),
// qiankun 插件配置
qiankun(APP_NAME, {
useDevMode: isDev, // 根据实际环境动态设置
}),
],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
"@public": resolve(__dirname, "public"),
},
// 设置条件导出优先使用 development
conditions: [ "development", "module", "import", "default" ],
},
// 优化依赖预构建,排除 workspace 包
optimizeDeps: {
exclude: [ "@venus/common-ui-vue", "jiti" ],
include: [],
},
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 不拆分
assetsDir: "assets", // 资源文件目录
rollupOptions: {
output: {
// qiankun 需要的输出格式
format: "umd",
// UMD 库名称,必须与应用名称一致
// eslint-disable-next-line unicorn/prefer-string-replace-all
name: `qiankunApp_${APP_NAME.replace(/-/g, "_")}`,
// 资源文件路径配置,Vite 会自动将 base 路径(/child/${APP_NAME}/)应用到这些路径
entryFileNames: "assets/[name].js",
chunkFileNames: "assets/[name].[hash].js",
assetFileNames: "assets/[name].[hash].[ext]",
// 内联所有动态导入,解决顶层 await 问题
inlineDynamicImports: true,
},
},
},
};
});
<script setup lang="ts"></script>
<template>
<div id="main-app">
<router-view />
</div>
<div id="main-app">
<router-view />
</div>
</template>
<style scoped>
#main-app {
width: 100%;
height: 100%;
min-height: 100vh;
width: 100%;
height: 100%;
min-height: 100vh;
}
</style>
......@@ -19,7 +19,9 @@ export interface RouteConfig {
isMicroApp?: boolean;
/** 是否需要认证 */
requiresAuth?: boolean;
/** 权限标识 */
/** 权限码(推荐使用,兼容 permission.md 设计) */
authority?: string | string[];
/** 权限标识(兼容旧版本) */
permissions?: string[];
/** 角色标识 */
roles?: string[];
......@@ -73,7 +75,8 @@ export function transformRouteConfig(config: RouteConfig): RouteRecordRaw {
level: config.level,
isMicroApp: config.isMicroApp,
requiresAuth: config.requiresAuth !== false,
permissions: config.permissions,
authority: config.authority, // 权限码(推荐使用)
permissions: config.permissions, // 兼容旧版本
roles: config.roles,
},
};
......
<template>
<slot v-if="hasPermission" />
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useUserStore } from "@/stores";
interface Props {
/** 权限码,支持字符串或字符串数组(满足任一即可) */
authority: string | string[];
}
const props = defineProps<Props>();
const userStore = useUserStore();
const hasPermission = computed(() => {
const authorities = Array.isArray(props.authority) ? props.authority : [ props.authority ];
return userStore.hasAuthority(authorities);
});
</script>
<script setup lang="ts">
import { useAppStore } from '@/stores';
import { useAppStore } from "@/stores";
const appStore = useAppStore();
</script>
<template>
<Transition name="fade">
<div v-if="appStore.loading" class="global-loading">
<div class="loading-content">
<div class="loading-spinner"></div>
<p class="loading-text">正在加载子应用...</p>
</div>
</div>
</Transition>
<Transition name="fade">
<div v-if="appStore.loading" class="global-loading">
<div class="loading-content">
<div class="loading-spinner"></div>
<p class="loading-text">
正在加载子应用...
</p>
</div>
</div>
</Transition>
</template>
<style scoped>
......
import { computed } from "vue";
import { useUserStore } from "@/stores";
export function useAuth() {
const userStore = useUserStore();
// 是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn);
// 用户信息
const userInfo = computed(() => userStore.userInfo);
// 角色列表
const roles = computed(() => userStore.roles);
// 权限列表
const authorities = computed(() => userStore.permissions);
/**
* 检查权限(支持 authority 字段)
*/
const hasAuthority = (authority: string | string[]) => {
return userStore.hasAuthority(authority);
};
/**
* 检查权限(兼容旧版本)
*/
const hasPermission = (permission: string | string[]) => {
return userStore.hasPermission(permission);
};
/**
* 检查角色
*/
const hasRole = (role: string | string[]) => {
return userStore.hasRole(role);
};
/**
* 登录
*/
const login = async (credentials: any) => {
return await userStore.login(credentials);
};
/**
* 登出
*/
const logout = async () => {
return await userStore.logout();
};
return {
isLoggedIn,
userInfo,
roles,
authorities,
hasAuthority,
hasPermission,
hasRole,
login,
logout,
};
}
/**
* 权限配置
* 包含权限白名单、超级管理员角色等配置
*/
/**
* 权限白名单配置
*/
export const PERMISSION_WHITELIST = {
// 路由白名单:不需要登录即可访问的路由(用于登录检查)
routes: [
'/login',
'/register',
'/forgot-password',
'/404',
'/403',
] as string[],
// 用户ID白名单:白名单内的用户默认可以访问全部权限
// 开发者可以在此配置需要拥有全部权限的用户ID
//
// 使用说明:
// 1. 将需要拥有全部权限的用户ID添加到数组中
// 2. 白名单内的用户将自动拥有所有权限,无需配置具体权限码
// 3. 注意:这里配置的是用户ID(如 '1', '2', 'admin-user-id'),不是用户名
//
// 示例:
// userIds: ['1', '2', 'admin-user-id'],
userIds: [
// 在此添加需要拥有全部权限的用户ID
// 示例:'1', '2', 'admin-user-id'
] as string[],
// 超级管理员角色(保留,作为备用方案)
// 如果用户角色包含 super-admin,也会拥有所有权限
roles: [
'super-admin', // 超级管理员
] as string[],
};
/**
* 检查路由是否在白名单中(用于登录检查)
*/
export function isRouteInWhitelist(path: string): boolean {
return PERMISSION_WHITELIST.routes.includes(path);
}
/**
* 检查用户ID是否在白名单中
* 白名单内的用户默认拥有所有权限
*/
export function isUserIdInWhitelist(userId: string): boolean {
return PERMISSION_WHITELIST.userIds.includes(userId);
}
/**
* 检查角色是否为超级管理员
*/
export function isSuperAdmin(role: string): boolean {
return PERMISSION_WHITELIST.roles.includes(role);
}
/**
* 检查角色列表是否包含超级管理员
*/
export function hasSuperAdminRole(roles: string[]): boolean {
return roles.some((role) => isSuperAdmin(role));
}
/**
* 权限指令
* 使用方式:v-auth="'system:user:add'" 或 v-auth="['system:user:add', 'system:user:edit']"
*/
import type { Directive } from 'vue';
import { useUserStore } from '@/stores';
export const auth: Directive = {
mounted(el, binding) {
const { value } = binding;
const userStore = useUserStore();
if (!value) return;
const authorities = Array.isArray(value) ? value : [value];
const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) {
el.parentNode?.removeChild(el);
}
},
updated(el, binding) {
const { value } = binding;
const userStore = useUserStore();
if (!value) return;
const authorities = Array.isArray(value) ? value : [value];
const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) {
// 如果元素已存在但无权限,移除它
if (el.parentNode) {
el.parentNode.removeChild(el);
}
} else {
// 如果有权限但元素不存在,需要重新添加(这种情况较少见)
// 这里不做处理,因为通常元素已经在 mounted 时被移除了
}
},
};
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import { fetchConfig } from './config/center';
import { setupQiankun } from './qiankun';
import router, { loadDynamicRoutes } from './router';
import { useAppStore, useUserStore } from './stores';
import { getToken } from './utils/auth';
import './styles/element/index.scss';
import 'element-plus/dist/index.css';
import './style.css';
import { createApp } from "vue";
import CommonUI from "@venus/common-ui-vue";
import { createPinia } from "pinia";
import App from "./App.vue";
import { fetchConfig } from "./config/center";
import { auth } from "./directives/auth";
import { setupQiankun } from "./qiankun";
import router, { loadDynamicRoutes } from "./router";
import { useAppStore, useUserStore } from "./stores";
import { getToken } from "./utils/auth";
import "./styles/element/index.scss";
import "element-plus/dist/index.css";
import "./style.css";
// 创建应用实例
const app = createApp(App);
// 注册通用 UI 组件库
app.use(CommonUI);
// 注册权限指令
app.directive("auth", auth);
// 创建 pinia 实例
const pinia = createPinia();
......@@ -23,73 +35,73 @@ app.use(router);
// 应用初始化
async function initApp() {
try {
// 初始化应用状态
const appStore = useAppStore();
appStore.initApp();
// 如果有 token,尝试恢复用户信息
const token = getToken();
if (token) {
const userStore = useUserStore();
userStore.setTokenValue(token);
// 尝试获取用户信息(如果失败,路由守卫会处理)
try {
await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单-性能优化层(预加载)- 有必要性
await loadDynamicRoutes();
} catch {
// console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
}
}
} catch (error) {
console.error('[基座] 应用初始化失败:', error);
}
try {
// 初始化应用状态
const appStore = useAppStore();
appStore.initApp();
// 如果有 token,尝试恢复用户信息
const token = getToken();
if (token) {
const userStore = useUserStore();
userStore.setTokenValue(token);
// 尝试获取用户信息(如果失败,路由守卫会处理)
try {
await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单-性能优化层(预加载)- 有必要性
await loadDynamicRoutes();
} catch {
// console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
}
}
} catch (error) {
console.error("[基座] 应用初始化失败:", error);
}
}
// 监听用户 Store 变化,自动同步到 qiankun 全局状态
function setupStoreSync() {
const userStore = useUserStore();
const appStore = useAppStore();
// 监听用户信息变化
userStore.$subscribe(() => {
// 每次 Store 变化时,同步用户信息
userStore.syncUserToQiankun();
});
// 监听主题变化,同步到 qiankun 全局状态
appStore.$subscribe((_mutation, state) => {
import('./qiankun/communication').then(({ communicationManager }) => {
communicationManager.updateTheme({
mode: state.theme,
primaryColor: state.theme === 'dark' ? '#177ddc' : '#1890ff',
});
});
});
const userStore = useUserStore();
const appStore = useAppStore();
// 监听用户信息变化
userStore.$subscribe(() => {
// 每次 Store 变化时,同步用户信息
userStore.syncUserToQiankun();
});
// 监听主题变化,同步到 qiankun 全局状态
appStore.$subscribe((_mutation, state) => {
import("./qiankun/communication").then(({ communicationManager }) => {
communicationManager.updateTheme({
mode: state.theme,
primaryColor: state.theme === "dark" ? "#177ddc" : "#1890ff",
});
});
});
}
// 获取配置中心配置
fetchConfig()
.then((config) => {
console.log('[基座] 当前配置数据:', config);
})
.catch((error) => {
console.error('[基座] 配置中心配置获取失败:', error);
})
.finally(() => {
// 初始化应用
initApp().then(() => {
// 挂载应用
app.mount('#app');
// 设置 Store 同步机制
setupStoreSync();
// 等待路由准备就绪后再启动 qiankun,避免刷新时容器未挂载的问题
router.isReady().then(() => {
// 启动 qiankun 微前端框架
setupQiankun();
});
});
});
.then((config) => {
console.log("[基座] 当前配置数据:", config);
})
.catch((error) => {
console.error("[基座] 配置中心配置获取失败:", error);
})
.finally(() => {
// 初始化应用
initApp().then(() => {
// 挂载应用
app.mount("#app");
// 设置 Store 同步机制
setupStoreSync();
// 等待路由准备就绪后再启动 qiankun,避免刷新时容器未挂载的问题
router.isReady().then(() => {
// 启动 qiankun 微前端框架
setupQiankun();
});
});
});
......@@ -7,6 +7,7 @@ import { getMicroAppByPath } from '@/qiankun/apps';
import { useAppStore, useMenuStore, useUserStore } from '@/stores';
import { getToken } from '@/utils/auth';
import { waitForMicroAppContainer } from '@/utils/microapp';
import { isRouteInWhitelist } from '@/config/permission';
/**
* 路由配置
......@@ -58,6 +59,16 @@ const routes: RouteRecordRaw[] = [
},
],
},
// ==================== 403 页面 ====================
{
path: '/403',
name: 'Forbidden',
component: () => import('@/views/Forbidden.vue'),
meta: {
title: '无权限访问',
requiresAuth: false,
},
},
// ==================== 404 页面 ====================
{
path: '/:pathMatch(.*)*',
......@@ -104,8 +115,8 @@ export function addRoutes(routes: RouteRecordRaw[], parentName?: string) {
}
}
// 白名单:不需要登录的路由
const whiteList = new Set(['/forgot-password', '/login', '/register']);
// 登录页路径
const LOGIN_PATH = '/login';
// 标记是否正在加载动态路由
let isLoadingRoutes = false;
......@@ -223,8 +234,48 @@ router.beforeEach(async (to, _from, next) => {
// 判断是否需要认证
const requiresAuth = to.meta.requiresAuth !== false;
// ==================== Token 检查 ====================
// 如果本地 token 不存在,检查访问权限
if (!token) {
// 明确声明忽略权限访问权限,则可以访问
if (to.meta.ignoreAccess) {
next();
return;
}
// 如果已经在登录页,直接放行
if (to.path === LOGIN_PATH) {
next();
return;
}
// 在白名单中,直接放行
if (isRouteInWhitelist(to.path)) {
next();
return;
}
// 不需要认证的页面,直接放行
if (!requiresAuth) {
next();
return;
}
// 没有访问权限,弹框提示后跳转登录页面
ElMessage.warning('登录已过期,请重新登录');
next({
path: LOGIN_PATH,
query:
to.fullPath === '/home' || to.fullPath === '/'
? {}
: { redirect: encodeURIComponent(to.fullPath) },
replace: true,
});
return;
}
// 如果匹配到404路由,检查是否是子应用路由
if (to.name === 'NotFound' && token) {
if (to.name === 'NotFound') {
const menuStore = useMenuStore();
// 优化:如果动态路由还未加载,才进行检查和加载
......@@ -253,88 +304,69 @@ router.beforeEach(async (to, _from, next) => {
return;
}
if (token) {
// 已登录
if (to.path === '/login') {
// 如果已登录,访问登录页则跳转到首页
next({ path: '/home' });
} else {
// 检查是否已获取用户信息
if (userStore.userInfo) {
// 检查权限
if (to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore);
if (hasPermission) {
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} else {
// 无权限,提示并跳转到登录页
ElMessage.error('无权限访问,请重新登录');
// await userStore.logout();
next({
path: '/login',
query: { redirect: to.fullPath },
});
}
} else {
// 如果是微应用路由,确保数据已同步并且容器已就绪
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
// 等待容器就绪
const isContainerReady = await waitForMicroAppContainer();
if (!isContainerReady) {
console.error('[路由守卫] 微应用容器未就绪,跳转可能失败');
}
}
next();
// ==================== 已登录状态处理 ====================
// 如果已登录,访问登录页则跳转到首页
if (to.path === LOGIN_PATH) {
next({ path: '/home' });
return;
}
// 已登录,处理其他路由
// 检查是否已获取用户信息
if (userStore.userInfo) {
// 检查权限(支持 authority、permissions 和 roles)
if (to.meta.authority || to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore);
if (hasPermission) {
// 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
}
next();
} else {
try {
// 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单
await loadDynamicRoutes();
// 如果是微应用路由,确保数据已同步并且容器已就绪
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
// 等待容器就绪
const isContainerReady = await waitForMicroAppContainer();
if (!isContainerReady) {
console.error('[路由守卫] 微应用容器未就绪,跳转可能失败');
}
}
next();
} catch {
// 获取用户信息失败,清除 token 并跳转到登录页
await userStore.logout();
next({
path: '/login',
query: { redirect: to.fullPath },
});
// 无权限,跳转到 403 页面
ElMessage.error('无权限访问该页面');
next('/403');
}
} else {
// 如果是微应用路由,确保数据已同步并且容器已就绪
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
// 等待容器就绪
const isContainerReady = await waitForMicroAppContainer();
if (!isContainerReady) {
console.error('[路由守卫] 微应用容器未就绪,跳转可能失败');
}
}
next();
}
} else {
// 未登录
if (whiteList.has(to.path)) {
// 在白名单中,直接放行
try {
// 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单
await loadDynamicRoutes();
// 如果是微应用路由,确保数据已同步并且容器已就绪
if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore);
// 等待容器就绪
const isContainerReady = await waitForMicroAppContainer();
if (!isContainerReady) {
console.error('[路由守卫] 微应用容器未就绪,跳转可能失败');
}
}
next();
} else if (requiresAuth) {
// 需要认证但未登录,跳转到登录页
} catch {
// 获取用户信息失败,清除 token 并跳转到登录页
ElMessage.warning('获取用户信息失败,请重新登录');
await userStore.logout();
next({
path: '/login',
path: LOGIN_PATH,
query: { redirect: to.fullPath },
});
} else {
// 不需要认证的页面,直接放行
next();
}
}
});
......@@ -383,8 +415,17 @@ async function syncDataToQiankun(userStore: any): Promise<void> {
/**
* 检查权限
* 支持 authority(推荐)、permissions 和 roles 三种方式
*/
function checkPermission(route: any, userStore: any): boolean {
// 优先检查 authority(推荐方式,兼容 permission.md 设计)
if (route.meta.authority) {
const authority = route.meta.authority as string | string[];
if (!userStore.hasAuthority(authority)) {
return false;
}
}
// 检查角色
if (route.meta.roles) {
const roles = route.meta.roles as string[];
......@@ -393,7 +434,7 @@ function checkPermission(route: any, userStore: any): boolean {
}
}
// 检查权限
// 检查权限(兼容旧版本)
if (route.meta.permissions) {
const permissions = route.meta.permissions as string[];
if (!userStore.hasPermission(permissions)) {
......
import type { RouteRecordRaw } from 'vue-router';
import type { RouteRecordRaw } from "vue-router";
import { ref } from 'vue';
import { ref } from "vue";
import { defineStore } from 'pinia';
import { defineStore } from "pinia";
/**
* 权限路由管理
*/
export const usePermissionStore = defineStore('permission', () => {
// 所有路由
const routes = ref<RouteRecordRaw[]>([]);
export const usePermissionStore = defineStore("permission", () => {
// 所有路由
const routes = ref<RouteRecordRaw[]>([]);
// 动态添加的路由
const dynamicRoutes = ref<RouteRecordRaw[]>([]);
// 动态添加的路由
const dynamicRoutes = ref<RouteRecordRaw[]>([]);
// 是否已生成路由
const isRoutesGenerated = ref(false);
// 是否已生成路由
const isRoutesGenerated = ref(false);
/**
/**
* 设置路由
*/
const setRoutes = (newRoutes: RouteRecordRaw[]) => {
routes.value = newRoutes;
};
const setRoutes = (newRoutes: RouteRecordRaw[]) => {
routes.value = newRoutes;
};
/**
/**
* 生成动态路由
* 根据用户权限过滤路由
*/
const generateRoutes = (roles: string[], permissions: string[]) => {
// 这里可以根据角色和权限动态生成路由
// 目前先返回所有路由,后续可以根据需求扩展
const generateRoutes = (roles: string[], permissions: string[]) => {
// 这里可以根据角色和权限动态生成路由
// 目前先返回所有路由,后续可以根据需求扩展
// 示例:根据角色过滤路由
const accessedRoutes = filterRoutes(routes.value, roles, permissions);
// 示例:根据角色过滤路由
const accessedRoutes = filterRoutes(routes.value, roles, permissions);
dynamicRoutes.value = accessedRoutes;
isRoutesGenerated.value = true;
dynamicRoutes.value = accessedRoutes;
isRoutesGenerated.value = true;
return accessedRoutes;
};
return accessedRoutes;
};
/**
/**
* 过滤路由
*/
const filterRoutes = (
routes: RouteRecordRaw[],
roles: string[],
permissions: string[],
): RouteRecordRaw[] => {
const res: RouteRecordRaw[] = [];
routes.forEach((route) => {
const tmp = { ...route };
// 检查路由权限
if (hasPermission(tmp, roles, permissions)) {
// 递归过滤子路由
if (tmp.children) {
tmp.children = filterRoutes(tmp.children, roles, permissions);
}
res.push(tmp);
}
});
return res;
};
/**
const filterRoutes = (
routes: RouteRecordRaw[],
roles: string[],
permissions: string[],
): RouteRecordRaw[] => {
const res: RouteRecordRaw[] = [];
routes.forEach((route) => {
const tmp = { ...route };
// 检查路由权限
if (hasPermission(tmp, roles, permissions)) {
// 递归过滤子路由
if (tmp.children) {
tmp.children = filterRoutes(tmp.children, roles, permissions);
}
res.push(tmp);
}
});
return res;
};
/**
* 判断是否有权限访问路由
*/
const hasPermission = (
route: RouteRecordRaw,
roles: string[],
permissions: string[],
): boolean => {
// 如果路由没有设置权限要求,默认可访问
if (!route.meta?.roles && !route.meta?.permissions) {
return true;
}
// 检查角色
if (route.meta?.roles) {
const routeRoles = route.meta.roles as string[];
if (roles.some((role) => routeRoles.includes(role))) {
return true;
}
}
// 检查权限
if (route.meta?.permissions) {
const routePermissions = route.meta.permissions as string[];
if (
permissions.some((permission) => routePermissions.includes(permission))
) {
return true;
}
}
return false;
};
/**
const hasPermission = (
route: RouteRecordRaw,
roles: string[],
permissions: string[],
): boolean => {
// 如果路由没有设置权限要求,默认可访问
if (!route.meta?.roles && !route.meta?.permissions) {
return true;
}
// 检查角色
if (route.meta?.roles) {
const routeRoles = route.meta.roles as string[];
if (roles.some((role) => routeRoles.includes(role))) {
return true;
}
}
// 检查权限
if (route.meta?.permissions) {
const routePermissions = route.meta.permissions as string[];
if (
permissions.some((permission) => routePermissions.includes(permission))
) {
return true;
}
}
return false;
};
/**
* 重置状态
*/
const reset = () => {
routes.value = [];
dynamicRoutes.value = [];
isRoutesGenerated.value = false;
};
return {
routes,
dynamicRoutes,
isRoutesGenerated,
setRoutes,
generateRoutes,
hasPermission,
reset,
};
const reset = () => {
routes.value = [];
dynamicRoutes.value = [];
isRoutesGenerated.value = false;
};
return {
routes,
dynamicRoutes,
isRoutesGenerated,
setRoutes,
generateRoutes,
hasPermission,
reset,
};
});
import type { LoginParams, UserInfo } from '@/types/user';
import { computed, ref } from 'vue';
import { ref, computed } from 'vue';
import {
getUserInfo as getUserInfoApi,
login as loginApi,
......@@ -10,6 +8,7 @@ import {
import { removeToken, setToken } from '@/utils/auth';
import { defineStore } from 'pinia';
import { clearConfigCache } from '@/config/center';
import { isUserIdInWhitelist, hasSuperAdminRole } from '@/config/permission';
// 可选:如果使用方案2,需要导入此函数
/**
......@@ -165,6 +164,27 @@ export const useUserStore = defineStore('user', () => {
};
/**
* 检查权限(支持 authority 字段,兼容 permission.md 设计)
* 白名单内的用户和超级管理员拥有所有权限
*/
const hasAuthority = (authority: string | string[]): boolean => {
const authorities = Array.isArray(authority) ? authority : [authority];
// 检查用户ID是否在白名单中,白名单内的用户拥有所有权限
if (userInfo.value?.id && isUserIdInWhitelist(userInfo.value.id)) {
return true;
}
// 超级管理员拥有所有权限
if (hasSuperAdminRole(roles.value)) {
return true;
}
// 检查是否有任一权限
return authorities.some((auth) => permissions.value.includes(auth));
};
/**
* 检查角色
*/
const hasRole = (role: string | string[]): boolean => {
......@@ -202,6 +222,7 @@ export const useUserStore = defineStore('user', () => {
getUserInfo,
setTokenValue,
hasPermission,
hasAuthority, // 新增:支持 authority 字段的权限检查
hasRole,
reset,
syncUserToQiankun, // 导出同步方法,供外部使用
......
/**
* 路由类型扩展
* 扩展 Vue Router 的 RouteMeta 接口,支持权限相关字段
*/
import 'vue-router';
declare module 'vue-router' {
interface RouteMeta {
/** 页面标题 */
title?: string;
/** 路由层级 */
level?: number;
/** 是否为微应用 */
isMicroApp?: boolean;
/** 是否需要认证 */
requiresAuth?: boolean;
/** 权限码(推荐使用,兼容 permission.md 设计) */
authority?: string | string[];
/** 权限标识(兼容旧版本) */
permissions?: string[];
/** 角色标识 */
roles?: string[];
/** 是否忽略访问权限检查 */
ignoreAccess?: boolean;
}
}
<template>
<div class="forbidden-container">
<div class="forbidden-content">
<div class="forbidden-icon">403</div>
<h1 class="forbidden-title">无权限访问</h1>
<p class="forbidden-description">抱歉,您没有权限访问该页面</p>
<div class="forbidden-actions">
<el-button type="primary" @click="goHome">返回首页</el-button>
<el-button @click="goBack">返回上一页</el-button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
router.push('/home');
};
const goBack = () => {
router.back();
};
</script>
<style scoped>
.forbidden-container {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.forbidden-content {
text-align: center;
color: #fff;
}
.forbidden-icon {
font-size: 120px;
font-weight: bold;
margin-bottom: 20px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.forbidden-title {
font-size: 32px;
margin-bottom: 16px;
font-weight: 600;
}
.forbidden-description {
font-size: 16px;
margin-bottom: 32px;
opacity: 0.9;
}
.forbidden-actions {
display: flex;
gap: 16px;
justify-content: center;
}
</style>
......@@ -100,8 +100,8 @@ const handleLogin = async () => {
loading.value = true;
try {
// 调用登录接口
const publicKey = await getPublicKey({});
// 调用登录接口: 数据加密处理+登录接口
const publicKey = await getPublicKey({}); // 获取公钥
const encryptedPassword = rsaEncrypt(loginForm?.password, publicKey?.data?.data);
let requestData = {
username: loginForm.username,
......
{
"compilerOptions": {
"composite": true,
"baseUrl": ".",
"module": "ESNext",
"moduleResolution": "bundler",
"paths": {
"@/*": ["src/*"]
},
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
import type { Plugin } from 'vite';
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { existsSync } from 'node:fs';
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 { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { defineConfig } from "vite";
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import AutoImport from 'unplugin-auto-import/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig } from 'vite';
// 获取源码路径
const commonUiSourcePath = resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
);
// 自定义插件:强制解析 @venus/common-ui-vue
function resolveWorkspacePackage(): Plugin {
return {
name: 'resolve-workspace-package',
enforce: 'pre', // 在其他插件之前执行
resolveId(id, importer) {
// 精确匹配包名
if (
id === '@venus/common-ui-vue' ||
id.startsWith('@venus/common-ui-vue/')
) {
// 验证文件是否存在
if (existsSync(commonUiSourcePath)) {
return {
id: commonUiSourcePath,
external: false,
};
}
console.warn(
`[resolve-workspace-package] 文件不存在: ${commonUiSourcePath}`,
);
}
return null;
},
};
}
// 获取 __dirname 的 ES 模块兼容方式
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default defineConfig({
plugins: [
resolveWorkspacePackage(),
vue(),
vueJsx(),
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
resolvers: [ElementPlusResolver()],
dts: 'src/auto-imports.d.ts',
}),
Components({
resolvers: [ElementPlusResolver()],
dts: 'src/components.d.ts',
}),
],
resolve: {
alias: [
{
find: '@',
replacement: resolve(__dirname, 'src'),
},
{
find: '@venus/common-ui-vue',
replacement: resolve(
__dirname,
'../../../../packages/common-ui/vue-ui/src/index.ts',
),
},
],
// 设置条件导出优先使用 development
conditions: ['development', 'module', 'import', 'default'],
},
// 优化依赖预构建,排除 workspace 包
optimizeDeps: {
exclude: ['@venus/common-ui-vue'],
include: [],
},
server: {
port: 8080,
cors: true,
host: true,
},
build: {
target: 'esnext',
minify: false,
cssCodeSplit: false,
},
plugins: [
vue(),
vueJsx(),
AutoImport({
imports: [ "vue", "vue-router", "pinia" ],
resolvers: [ ElementPlusResolver() ],
dts: "src/auto-imports.d.ts",
}),
Components({
resolvers: [ ElementPlusResolver() ],
dts: "src/components.d.ts",
}),
],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
// 配置条件导出优先级,让打包时也使用 development 模式的源码
conditions: [ "development", "module", "import", "default" ],
},
// 优化依赖预构建,排除 workspace 包
optimizeDeps: {
exclude: [ "@venus/common-ui-vue" ],
include: [],
},
server: {
port: 8080,
cors: true,
host: true,
},
build: {
target: "esnext",
minify: false,
cssCodeSplit: false,
},
});
......@@ -23,7 +23,7 @@ export default defineConfig({
text: '相关链接',
items: [
{
text: 'GitLab',
text: 'Venus GitLab',
link: 'http://192.168.3.233:8090/monorepo/venus.git',
},
{
......@@ -34,7 +34,6 @@ export default defineConfig({
],
},
],
sidebar: {
'/guide/': [
{
......@@ -49,6 +48,7 @@ export default defineConfig({
text: '基础',
items: [
{ text: '目录结构', link: '/guide/directory-structure' },
{ text: '构建说明', link: '/guide/buildREADME' },
{ text: '路由和菜单', link: '/guide/router-menu' },
{ text: '权限管理', link: '/guide/permission' },
{ text: '状态管理', link: '/guide/state-management' },
......@@ -64,6 +64,25 @@ export default defineConfig({
],
},
],
'/micro/': [
{
text: '开始',
items: [
{ text: '简介', link: '/guide/introduction' },
{ text: '快速开始', link: '/guide/quick-start' },
{ text: '项目配置', link: '/guide/configuration' },
],
},
{
text: '基础',
items: [
{ text: '目录结构', link: '/guide/directory-structure' },
{ text: '路由和菜单', link: '/guide/router-menu' },
{ text: '权限管理', link: '/guide/permission' },
{ text: '状态管理', link: '/guide/state-management' },
],
},
],
'/components/': [
{
text: '组件',
......
# Venus CLI 使用指南
## 概述
Venus CLI 是一个项目模板构建框架,可以快速创建 React 或 Vue 项目到 `apps` 目录中。
## 安装和构建
### 首次安装
```bash
# 安装依赖
pnpm install
# 构建 CLI(首次安装会自动执行)
pnpm venus:build
```
### 重新构建 CLI
如果修改了 CLI 源码,需要重新构建:
```bash
pnpm venus:build
```
## 基本用法
### 查看帮助
```bash
pnpm venus --help
```
### 列出可用模板
```bash
pnpm venus:ls
# 或
pnpm venus ls-templates
```
输出示例:
```
- react: eslint; router; store; ui: [antd]
- vue: eslint; router; store; ui: [element-plus]
```
### 创建项目
#### 创建基础 React 项目
```bash
pnpm venus create my-react-app --template react --no-install
```
#### 创建完整配置的 React 项目
```bash
pnpm venus create my-app --template react --router --store --ui antd --eslint --no-install
```
#### 创建 Vue 项目
```bash
pnpm venus create my-vue-app --template vue --router --store --ui element-plus --eslint --no-install
```
## 命令选项说明
### `venus create <name> [options]`
创建一个新的前端项目。
**必需参数:**
- `<name>` - 项目名称
**可选参数:**
- `--template <name>` - 选择模板(react 或 vue),默认 react
- `--dir <path>` - 自定义生成目录前缀,最终路径为 `<dir>/<name>`
- `--root <path>` - 指定生成根目录,默认当前工作目录
- `--no-install` - 跳过依赖安装
- `--router` - 注入路由支持
- React: react-router-dom
- Vue: vue-router
- `--store` - 注入状态管理
- React: zustand
- Vue: pinia
- `--ui <name>` - 注入 UI 库
- React: antd
- Vue: element-plus
- `--eslint` - 注入 ESLint 配置
- `--force` - 目标目录非空时强制写入(危险操作,谨慎使用)
## 默认目录结构
项目将按照以下默认路径创建:
- **React 项目**: `apps/frontend/react/<name>`
- **Vue 项目**: `apps/frontend/vue/<name>`
你可以使用 `--dir` 选项自定义目录。
## 使用示例
### 示例 1: 创建简单的 React 项目
```bash
pnpm venus create simple-app --template react --no-install
cd apps/frontend/react/simple-app
pnpm install
pnpm run dev
```
### 示例 2: 创建包含所有功能的 React 项目
```bash
pnpm venus create full-app --template react --router --store --ui antd --eslint --no-install
cd apps/frontend/react/full-app
pnpm install
pnpm run dev
```
### 示例 3: 创建自定义路径的项目
```bash
pnpm venus create custom-app --template react --dir apps/custom --no-install
cd apps/custom/custom-app
pnpm install
pnpm run dev
```
### 示例 4: 创建 Vue 项目(完整配置)
```bash
pnpm venus create vue-app --template vue --router --store --ui element-plus --eslint --no-install
cd apps/frontend/vue/vue-app
pnpm install
pnpm run dev
```
## 全局安装(可选)
如果希望在系统任何位置都能使用 `venus` 命令:
### Windows
```bash
# 1. 配置 pnpm
pnpm setup
# 2. 全局链接 CLI
pnpm -C packages/cli link --global
# 3. 重新打开终端,然后可以直接使用
venus --help
```
### Linux / macOS
```bash
# 1. 配置 pnpm
pnpm setup
# 2. 全局链接 CLI
pnpm -C packages/cli link --global
# 3. 刷新终端配置
source ~/.bashrc # 或 source ~/.zshrc
# 4. 直接使用
venus --help
```
## 模板特性说明
### React 模板特性
- **基础**: Vite + React + TypeScript
- **router**: 自动配置 React Router,入口文件已包裹 BrowserRouter
- **store**: 使用 Zustand 提供计数器示例
- **ui (antd)**: 引入 Ant Design,包含示例组件
- **eslint**: 基础 ESLint 配置
### Vue 模板特性
- **基础**: Vite + Vue 3 + TypeScript
- **router**: 生成 router.ts,需在 main.ts 中手动 `app.use(router)`
- **store**: 生成 Pinia store,需在 main.ts 中手动 `app.use(pinia)`
- **ui (element-plus)**: 生成 ui.ts,需在 main.ts 中调用 `setupUI(app)`
- **eslint**: 基础 ESLint 配置
**Vue 项目手动接入示例 (main.ts):**
```typescript
import { createApp } from "vue";
import App from "./App.vue";
import { router } from "./router";
import { pinia } from "./store";
import { setupUI } from "./ui";
const app = createApp(App);
app.use(router);
app.use(pinia);
setupUI(app);
app.mount("#app");
```
## 构建整个工作区
如果需要构建整个工作区的所有包:
```bash
pnpm venus build
```
这将执行 `scripts/build.js`,构建所有工作区包。
## 常见问题
### Q1: `venus` 命令找不到?
**A**: 在项目内使用时,请使用 `pnpm venus` 而不是直接使用 `venus`。或者按照上面的说明进行全局安装。
### Q2: 创建项目后提示目录已存在?
**A**: 默认情况下,CLI 会保护非空目录。如果确定要覆盖,请使用 `--force` 选项,但请注意这会覆盖现有文件。
### Q3: 模板可选特性没有生效?
**A**:
- React Router 会自动生效(入口文件已配置)
- Vue 的可选特性需要在 `main.ts` 中手动接入(参考上面的示例)
### Q4: CLI 源码修改后没有生效?
**A**: 修改 CLI 源码后需要重新构建:
```bash
pnpm venus:build
```
### Q5: 如何添加新的模板或 UI 库?
**A**:
1. 在 `packages/cli/templates` 下创建新的模板目录
2. 在 `optional/ui` 下添加新的 UI 库配置
3. 重新构建 CLI
## 技术细节
### 占位符替换
模板中使用 `__APP_NAME__` 作为占位符,创建项目时会自动替换为实际的项目名称。
### 依赖合并
可选特性通过 `_package.merge.json` 文件定义需要添加的依赖,CLI 会自动合并到目标项目的 `package.json` 中。
### 构建系统
CLI 使用 Rollup 进行构建,配置文件位于 `scripts/build/` 目录:
- `buildBase.js` - 基础构建配置
- `buildSingle.js` - 单包构建脚本
- `build.js` - 全量构建脚本
## 相关文件
- **CLI 源码**: `packages/cli/src/index.ts`
- **模板目录**: `packages/cli/templates/`
- **构建脚本**: `scripts/build/`
- **CLI 配置**: `packages/cli/package.json`
## 快捷命令总结
```bash
# 列出可用模板
pnpm venus:ls
# 创建项目
pnpm venus:create <name> [options]
# 重新构建 CLI
pnpm venus:build
# 查看帮助
pnpm venus --help
# 查看版本
pnpm venus --version
```
## 贡献
如需添加新的模板或功能,请:
1. 修改 `packages/cli/src/index.ts`
2. 添加相应的模板文件
3. 运行 `pnpm venus:build` 重新构建
4. 测试功能是否正常
---
更多详细信息请参考 `packages/cli/Readme.md`
# 子应用通信模块重构说明
## 重构目标
将子应用的 `communication.ts` 重构为轻量级版本,直接使用基座通过 props 下发的通信管理器实例,避免维护本地实现。
## 主要变化
### 1. **communication.ts 重构**
#### 之前的实现
- 包含完整的本地通信管理器实现(`LocalSubAppCommunicationManager`)
- 包含降级方案逻辑
- 代码量约 287 行,逻辑复杂
#### 现在的实现
- 仅保留类型定义和接口(与基座保持一致)
- 移除所有本地实现逻辑
- 通过全局变量存储基座传递的实例
- 提供简洁的工具函数封装
- 代码量约 200 行,逻辑清晰
**核心代码结构:**
```typescript
// 1. 类型定义(与基座保持一致)
export interface GlobalState { ... }
export interface Notification { ... }
export interface SubAppCommunicationManager { ... }
// 2. 全局实例存储
let communicationManagerInstance: SubAppCommunicationManager | null = null;
// 3. 实例管理函数
export function setCommunicationManager(manager) { ... }
export function getCommunicationManager() { ... }
// 4. 便捷工具函数
export function useGlobalState(callback) { ... }
export function notify(type, title, message) { ... }
export const subAppCommunication = new Proxy(...) // 兼容旧代码
```
### 2. **main.ts 简化**
#### 之前的逻辑
```typescript
// 复杂的判断逻辑,包含降级方案
if (props.communicationManager) {
setCommunicationManager(props.communicationManager);
props.communicationManager.init(props);
} else if (props.onGlobalStateChange) {
// 降级方案
subAppCommunication.init(props);
}
```
#### 现在的逻辑
```typescript
// 简洁直接,只使用基座传递的实例
if (props.communicationManager) {
setCommunicationManager(props.communicationManager);
props.communicationManager.init(props);
app.config.globalProperties.$communication = props.communicationManager;
} else {
console.error("[子应用] 基座未传递通信管理器");
}
```
### 3. **类型安全增强**
- 所有类型定义在子应用中明确声明,避免跨项目导入问题
- 与基座类型定义保持完全一致
- 保持完整的 TypeScript 类型检查
## 架构流程
```
┌─────────────────────────────────────────────────────────┐
│ 微前端基座 │
│ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ CommunicationManager (基座通信管理器) │ │
│ │ - 管理全局状态 │ │
│ │ - 监听状态变化 │ │
│ │ - 广播通知 │ │
│ └──────────────────┬───────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼───────────────────────────────┐ │
│ │ SubAppCommunicationAdapter (子应用适配器) │ │
│ │ - 适配基座管理器到子应用接口 │ │
│ │ - 处理状态同步 │ │
│ │ - 实现 SubAppCommunicationManager 接口 │ │
│ └──────────────────┬───────────────────────────────┘ │
│ │ │
└─────────────────────┼───────────────────────────────────┘
│ props.communicationManager
│ (通过 qiankun 传递)
┌─────────────────────▼───────────────────────────────────┐
│ Vue3 子应用 │
│ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ main.ts │ │
│ │ - 接收 props.communicationManager │ │
│ │ - 调用 setCommunicationManager() │ │
│ │ - 初始化实例 │ │
│ └──────────────────┬───────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼───────────────────────────────┐ │
│ │ communication.ts (轻量级) │ │
│ │ - 存储实例引用 │ │
│ │ - 提供工具函数 │ │
│ │ - 导出类型定义 │ │
│ └──────────────────┬───────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼───────────────────────────────┐ │
│ │ 组件使用 │ │
│ │ - useGlobalState(callback) │ │
│ │ - notify(type, title, message) │ │
│ │ - subAppCommunication.xxx() │ │
│ └──────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────┘
```
## 优势
### 1. **代码简化**
- 移除 287 行的复杂实现,保留核心功能
- 不再需要维护本地降级方案
- 代码更易理解和维护
### 2. **统一管理**
- 通信逻辑完全由基座控制
- 确保所有子应用使用相同的通信机制
- 便于统一升级和修改
### 3. **类型安全**
- 类型定义在子应用中明确声明
- 避免跨项目导入的复杂性
- 保持完整的 TypeScript 支持
### 4. **向后兼容**
- 保留 `useGlobalState`、`notify`、`subAppCommunication` 等 API
- 组件代码无需修改
- 平滑迁移
## 使用示例
### 在组件中监听全局状态
```typescript
import { useGlobalState } from "@/utils/communication";
import type { GlobalState } from "@/utils/communication";
// 在 setup 中使用
useGlobalState((state: GlobalState, prev: GlobalState) => {
console.log("状态更新:", state);
// 处理状态变化
});
```
### 发送通知到基座
```typescript
import { notify } from "@/utils/communication";
// 发送成功通知
notify("success", "操作成功", "数据已保存");
// 发送错误通知
notify("error", "操作失败", "网络连接错误");
```
### 直接使用通信管理器
```typescript
import { subAppCommunication } from "@/utils/communication";
// 获取当前状态
const state = subAppCommunication.getCurrentState();
// 设置全局状态
subAppCommunication.setGlobalState({
theme: { mode: "dark", primaryColor: "#1890ff" },
});
```
## 注意事项
### 1. **基座依赖**
子应用现在完全依赖基座传递通信管理器实例,如果基座未传递:
- 会在控制台输出错误日志
- 通信功能不可用
- 不会影响应用其他功能
### 2. **类型同步**
当基座的类型定义发生变化时,需要同步更新子应用的类型定义,保持一致性。
### 3. **独立运行**
在独立运行模式下(不通过基座加载),通信功能不可用,但不会影响应用正常运行。
## 后续优化建议
### 1. **类型共享**
可以考虑将类型定义提取到独立的 npm 包或 monorepo 共享包中,避免重复定义。
### 2. **TypeScript Path Mapping**
配置 TypeScript 路径映射,直接从基座导入类型:
```json
{
"compilerOptions": {
"paths": {
"@base/*": ["../venus-base/src/*"]
}
}
}
```
### 3. **运行时类型检查**
添加运行时类型检查,确保基座传递的实例符合预期接口。
## 总结
此次重构将子应用的通信模块从"自主实现+降级方案"改为"完全依赖基座",实现了:
- ✅ 代码大幅简化
- ✅ 职责更加清晰
- ✅ 维护成本降低
- ✅ 保持向后兼容
- ✅ 类型安全保证
这是微前端架构中"基座控制,子应用依赖"模式的最佳实践。
# Venus Admin 文档
# Venus 文档
欢迎使用 Venus Admin 文档!
欢迎使用 Venus 文档!
这是基于 VitePress 构建的文档站点,包含了 Venus Admin 的完整使用指南、API 参考和最佳实践。
这是基于 VitePress 构建的文档站点,包含了 Venus 的完整使用指南、API 参考和最佳实践。
## 快速开始
......
# Scripts 命令文档
本文档说明了 `package.json` 中所有 script 命令的作用。
## 开发相关
### `dev`
启动开发服务器,运行所有包/应用的开发模式。
```bash
pnpm dev
```
### `dev:docs`
启动文档开发服务器。
```bash
pnpm dev:docs
```
### `preview`
预览构建后的应用。
```bash
pnpm preview
```
## 构建相关
### `build`
构建项目(使用 turbo-run,设置内存限制为 8GB)。
```bash
pnpm build
```
### `build:all`
构建所有项目(使用 turbo,设置内存限制为 8GB)。
```bash
pnpm build:all
```
### `build:filter`
按过滤条件构建并复制到根目录。
```bash
pnpm build:filter
```
### `build:docs`
构建文档项目。
```bash
pnpm build:docs
```
## 代码质量检查
### `check`
运行所有检查:循环依赖、依赖、类型检查、拼写检查。
```bash
pnpm check
```
### `check:circular`
检查代码中的循环依赖。
```bash
pnpm check:circular
```
### `check:dep`
检查依赖关系。
```bash
pnpm check:dep
```
### `check:type`
运行 TypeScript 类型检查。
```bash
pnpm check:type
```
### `check:cspell`
对代码和文档进行拼写检查。
```bash
pnpm check:cspell
```
### `lint`
运行 ESLint 代码检查。
```bash
pnpm lint
```
### `format`
格式化代码(自动修复格式问题)。
```bash
pnpm format
```
### `publint`
发布前对包进行 lint 检查。
```bash
pnpm publint
```
## 测试相关
### `test:unit`
运行单元测试(使用 Vitest,DOM 环境)。
```bash
pnpm test:unit
```
### `test:e2e`
运行端到端测试(使用 Playwright)。
```bash
pnpm test:e2e
```
### `command:test`
测试构建命令。
```bash
pnpm command:test
```
## 依赖管理
### `update:deps`
交互式更新所有依赖到最新版本。
```bash
pnpm update:deps
```
### `reinstall`
清理并重新安装依赖(删除锁文件后重新安装)。
```bash
pnpm reinstall
```
### `clean`
清理构建产物和临时文件。
```bash
pnpm clean
```
## 版本管理
### `changeset`
创建变更集(用于版本管理和生成 CHANGELOG)。
```bash
pnpm changeset
```
### `version`
更新版本号并更新锁文件(通常在发布前使用)。
```bash
pnpm version
```
### `catalog`
运行 pnpm catalog codemod(管理依赖目录)。
```bash
pnpm catalog
```
## Venus CLI 相关
### `venus`
运行 Venus CLI 工具。
```bash
pnpm venus
```
### `venus:build`
构建 Venus CLI 工具。
```bash
pnpm venus:build
```
### `venus:create`
创建新的 Venus 项目。
```bash
pnpm venus:create
```
### `venus:create:interactive`
交互式创建新的 Venus 项目。
```bash
pnpm venus:create:interactive
```
### `venus:ls`
列出可用的 Venus 模板。
```bash
pnpm venus:ls
```
## Git 相关
### `commit`
使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。
```bash
pnpm commit
```
## 生命周期钩子
### `preinstall`
安装前钩子:强制使用 pnpm 作为包管理器。
### `postinstall`
安装后钩子:在所有包中运行 stub 脚本(如果存在)。
### `prepare`
初始化 Husky Git hooks。
# 核心 API
Venus Admin 提供的核心 API 接口。
## useUserStore
用户状态管理。
### 类型定义
```typescript
interface UserInfo {
id: string;
username: string;
email: string;
avatar: string;
roles: string[];
authorities: string[];
}
interface UserStore {
userInfo: UserInfo | null;
token: string | null;
// Getters
isLoggedIn: boolean;
getUserInfo: UserInfo | null;
// Actions
setUserInfo(userInfo: UserInfo): void;
setToken(token: string): void;
login(credentials: LoginCredentials): Promise<UserInfo>;
logout(): Promise<void>;
fetchUserInfo(): Promise<UserInfo>;
}
```
### 使用示例
```typescript
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();
// 获取用户信息
const userInfo = userStore.userInfo;
// 登录
await userStore.login({
username: "admin",
password: "123456",
});
// 登出
await userStore.logout();
```
## useAuthStore
权限状态管理。
### 类型定义
```typescript
interface AuthStore {
roles: string[];
authorities: string[];
isDynamicRouteAdded: boolean;
// Actions
setRoles(roles: string[]): void;
setAuthorities(authorities: string[]): void;
hasAuthority(authority: string | string[]): boolean;
hasRole(role: string | string[]): boolean;
fetchUserRoutes(): Promise<RouteRecordRaw[]>;
}
```
### 使用示例
```typescript
import { useAuthStore } from "@/store/modules/auth";
const authStore = useAuthStore();
// 检查权限
const canAdd = authStore.hasAuthority("system:user:add");
// 检查角色
const isAdmin = authStore.hasRole("admin");
```
## useAppStore
应用状态管理。
### 类型定义
```typescript
interface AppStore {
collapsed: boolean;
theme: "light" | "dark";
locale: string;
// Actions
toggleCollapsed(): void;
setTheme(theme: "light" | "dark"): void;
setLocale(locale: string): void;
}
```
### 使用示例
```typescript
import { useAppStore } from "@/store/modules/app";
const appStore = useAppStore();
// 切换侧边栏折叠状态
appStore.toggleCollapsed();
// 切换主题
appStore.setTheme("dark");
// 切换语言
appStore.setLocale("en-US");
```
## useAuth
权限相关的组合式 API。
### 类型定义
```typescript
function useAuth(): {
isLoggedIn: ComputedRef<boolean>;
userInfo: ComputedRef<UserInfo | null>;
hasAuthority: (authority: string | string[]) => boolean;
hasRole: (role: string | string[]) => boolean;
login: (credentials: LoginCredentials) => Promise<UserInfo>;
logout: () => Promise<void>;
};
```
### 使用示例
```typescript
import { useAuth } from "@/composables/useAuth";
const { isLoggedIn, userInfo, hasAuthority, hasRole, login, logout } = useAuth();
// 检查是否登录
if (isLoggedIn.value) {
console.log("已登录");
}
// 检查权限
if (hasAuthority("system:user:add")) {
// 有权限
}
```
## useRequest
请求相关的组合式 API。
### 类型定义
```typescript
function useRequest<T>(
service: (...args: any[]) => Promise<T>,
options?: {
manual?: boolean;
defaultParams?: any[];
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
},
): {
data: Ref<T | undefined>;
loading: Ref<boolean>;
error: Ref<Error | undefined>;
run: (...args: any[]) => Promise<T>;
refresh: () => Promise<T>;
cancel: () => void;
};
```
### 使用示例
```typescript
import { useRequest } from "@/composables/useRequest";
import { getUserList } from "@/api/user";
const { data, loading, run } = useRequest(getUserList, {
defaultParams: [{ page: 1, pageSize: 10 }],
onSuccess: (data) => {
console.log("请求成功", data);
},
});
// 手动触发请求
run({ page: 2 });
```
## useTable
表格相关的组合式 API。
### 类型定义
```typescript
function useTable<T>(
service: (params: any) => Promise<{ list: T[]; total: number }>,
options?: {
defaultPageSize?: number;
},
): {
dataSource: Ref<T[]>;
loading: Ref<boolean>;
pagination: Ref<Pagination>;
refresh: () => Promise<void>;
search: (params: any) => Promise<void>;
reset: () => Promise<void>;
};
```
### 使用示例
```typescript
import { useTable } from "@/composables/useTable";
import { getUserList } from "@/api/user";
const { dataSource, loading, pagination, refresh, search, reset } = useTable(getUserList);
// 搜索
search({ keyword: "test" });
// 重置
reset();
// 刷新
refresh();
```
## useForm
表单相关的组合式 API。
### 类型定义
```typescript
function useForm<T>(options?: { initialValues?: Partial<T>; onSubmit?: (values: T) => void | Promise<void> }): {
formData: Ref<T>;
loading: Ref<boolean>;
errors: Ref<Record<string, string>>;
setFieldValue: (field: keyof T, value: any) => void;
setFieldError: (field: keyof T, error: string) => void;
validate: () => Promise<T>;
reset: () => void;
submit: () => Promise<void>;
};
```
### 使用示例
```typescript
import { useForm } from "@/composables/useForm";
const { formData, loading, errors, setFieldValue, validate, reset, submit } = useForm({
initialValues: {
username: "",
email: "",
},
onSubmit: async (values) => {
await saveUser(values);
},
});
// 设置字段值
setFieldValue("username", "admin");
// 提交表单
await submit();
```
## useModal
弹窗相关的组合式 API。
### 类型定义
```typescript
function useModal(): {
visible: Ref<boolean>;
loading: Ref<boolean>;
open: () => void;
close: () => void;
toggle: () => void;
setLoading: (loading: boolean) => void;
};
```
### 使用示例
```typescript
import { useModal } from "@/composables/useModal";
const { visible, loading, open, close, setLoading } = useModal();
// 打开弹窗
open();
// 关闭弹窗
close();
// 设置加载状态
setLoading(true);
```
# 类型定义
Venus Admin 提供的 TypeScript 类型定义。
## 用户相关
### UserInfo
用户信息类型。
```typescript
interface UserInfo {
/** 用户 ID */
id: string;
/** 用户名 */
username: string;
/** 昵称 */
nickname?: string;
/** 邮箱 */
email: string;
/** 手机号 */
phone?: string;
/** 头像 */
avatar?: string;
/** 角色列表 */
roles: string[];
/** 权限列表 */
authorities: string[];
/** 创建时间 */
createdAt: string;
/** 更新时间 */
updatedAt: string;
}
```
### LoginCredentials
登录凭证类型。
```typescript
interface LoginCredentials {
/** 用户名 */
username: string;
/** 密码 */
password: string;
/** 验证码 */
captcha?: string;
/** 记住我 */
rememberMe?: boolean;
}
```
## 路由相关
### RouteMeta
路由元信息类型。
```typescript
interface RouteMeta {
/** 路由标题 */
title: string;
/** 图标 */
icon?: string;
/** 排序 */
order?: number;
/** 是否隐藏在菜单中 */
hideInMenu?: boolean;
/** 是否隐藏子菜单 */
hideChildrenInMenu?: boolean;
/** 是否隐藏在面包屑中 */
hideInBreadcrumb?: boolean;
/** 是否隐藏在标签页中 */
hideInTabs?: boolean;
/** 是否固定在标签页中 */
affixTab?: boolean;
/** 当前激活的菜单 */
activeMenu?: string;
/** 权限码 */
authority?: string[];
/** 角色 */
roles?: string[];
/** 是否缓存 */
keepAlive?: boolean;
/** 外部链接 */
link?: string;
/** 是否为全屏页面 */
isFullscreen?: boolean;
/** 是否忽略权限 */
ignoreAccess?: boolean;
}
```
## 表格相关
### TableColumn
表格列配置类型。
```typescript
interface TableColumn<T = any> {
/** 列标题 */
title: string;
/** 数据字段 */
dataIndex: string;
/** 列的唯一标识 */
key: string;
/** 列宽度 */
width?: number | string;
/** 对齐方式 */
align?: "left" | "center" | "right";
/** 固定列 */
fixed?: "left" | "right";
/** 是否可排序 */
sorter?: boolean | ((a: T, b: T) => number);
/** 筛选配置 */
filters?: Filter[];
/** 自定义渲染 */
customRender?: (params: { record: T; index: number; column: TableColumn<T> }) => VNode | string;
}
```
### Pagination
分页配置类型。
```typescript
interface Pagination {
/** 当前页 */
current: number;
/** 每页条数 */
pageSize: number;
/** 总条数 */
total: number;
/** 是否显示 size 切换器 */
showSizeChanger?: boolean;
/** 是否显示快速跳转 */
showQuickJumper?: boolean;
/** 显示总数 */
showTotal?: (total: number) => string;
/** 每页条数选项 */
pageSizeOptions?: number[];
}
```
## 表单相关
### FormSchema
表单配置类型。
```typescript
interface FormSchema {
/** 字段名 */
field: string;
/** 标签 */
label: string;
/** 组件类型 */
component: ComponentType;
/** 是否必填 */
required?: boolean;
/** 验证规则 */
rules?: Rule[];
/** 组件属性 */
componentProps?: Record<string, any>;
/** 默认值 */
defaultValue?: any;
/** 是否显示 */
show?: boolean | ((formData: any) => boolean);
/** 是否禁用 */
disabled?: boolean | ((formData: any) => boolean);
/** 帮助文本 */
helpText?: string;
/** 占位符 */
placeholder?: string;
/** 栅格布局 */
colProps?: ColProps;
}
```
### Rule
表单验证规则类型。
```typescript
interface Rule {
/** 是否必填 */
required?: boolean;
/** 错误提示 */
message?: string;
/** 类型验证 */
type?: "string" | "number" | "boolean" | "url" | "email";
/** 最小长度 */
min?: number;
/** 最大长度 */
max?: number;
/** 固定长度 */
len?: number;
/** 正则验证 */
pattern?: RegExp;
/** 自定义验证 */
validator?: (rule: Rule, value: any) => boolean | Promise<boolean>;
/** 触发时机 */
trigger?: "change" | "blur";
}
```
## API 相关
### ApiResponse
API 响应类型。
```typescript
interface ApiResponse<T = any> {
/** 状态码 */
code: number;
/** 响应数据 */
data: T;
/** 响应消息 */
message: string;
/** 是否成功 */
success: boolean;
/** 时间戳 */
timestamp: number;
}
```
### PageResult
分页结果类型。
```typescript
interface PageResult<T = any> {
/** 数据列表 */
list: T[];
/** 总条数 */
total: number;
/** 当前页 */
page: number;
/** 每页条数 */
pageSize: number;
/** 总页数 */
totalPages: number;
}
```
### PageParams
分页参数类型。
```typescript
interface PageParams {
/** 当前页 */
page: number;
/** 每页条数 */
pageSize: number;
/** 排序字段 */
sortField?: string;
/** 排序方式 */
sortOrder?: "asc" | "desc";
/** 其他查询参数 */
[key: string]: any;
}
```
## 主题相关
### ThemeConfig
主题配置类型。
```typescript
interface ThemeConfig {
/** 主题模式 */
mode: "light" | "dark" | "auto";
/** 主题色 */
colorPrimary: string;
/** 成功色 */
colorSuccess?: string;
/** 警告色 */
colorWarning?: string;
/** 错误色 */
colorError?: string;
/** 信息色 */
colorInfo?: string;
/** 圆角 */
radius?: string;
}
```
## 应用配置
### AppConfig
应用配置类型。
```typescript
interface AppConfig {
/** 应用名称 */
name: string;
/** 应用版本 */
version: string;
/** 是否启用动态标题 */
enableDynamicTitle: boolean;
/** 是否启用检查更新 */
enableCheckUpdates: boolean;
/** 水印配置 */
watermark: boolean | WatermarkConfig;
}
```
### LayoutConfig
布局配置类型。
```typescript
interface LayoutConfig {
/** 布局模式 */
mode: "sidebar" | "mix" | "header";
/** 内容区域宽度 */
contentCompact: "wide" | "fixed";
/** 侧边栏配置 */
sidebar: SidebarConfig;
/** 头部配置 */
header: HeaderConfig;
/** 标签页配置 */
tabbar: TabbarConfig;
/** 页脚配置 */
footer: FooterConfig;
}
```
## 工具类型
### Recordable
可记录对象类型。
```typescript
type Recordable<T = any> = Record<string, T>;
```
### Nullable
可空类型。
```typescript
type Nullable<T> = T | null;
```
### NonNullable
非空类型。
```typescript
type NonNullable<T> = T extends null | undefined ? never : T;
```
### DeepPartial
深度可选类型。
```typescript
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
```
### DeepRequired
深度必填类型。
```typescript
type DeepRequired<T> = {
[P in keyof T]-?: T[P] extends object ? DeepRequired<T[P]> : T[P];
};
```
# 工具函数
Venus Admin 提供的常用工具函数。
## 通用工具
### is
类型判断工具。
```typescript
import { is } from "@venus/utils";
// 判断类型
is.string("hello"); // true
is.number(123); // true
is.boolean(true); // true
is.array([]); // true
is.object({}); // true
is.function(() => {}); // true
is.null(null); // true
is.undefined(undefined); // true
// 判断空值
is.empty(""); // true
is.empty([]); // true
is.empty({}); // true
is.empty(null); // true
is.empty(undefined); // true
// 判断浏览器环境
is.browser(); // true
is.mobile(); // false
is.ios(); // false
is.android(); // false
```
### cloneDeep
深拷贝。
```typescript
import { cloneDeep } from "@venus/utils";
const obj = { a: 1, b: { c: 2 } };
const cloned = cloneDeep(obj);
```
### merge
深度合并。
```typescript
import { merge } from "@venus/utils";
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const merged = merge(obj1, obj2);
// { a: 1, b: { c: 2, d: 3 }, e: 4 }
```
## 字符串工具
### formatDate
日期格式化。
```typescript
import { formatDate } from "@venus/utils";
// 格式化日期
formatDate(new Date(), "YYYY-MM-DD"); // '2024-01-01'
formatDate(new Date(), "YYYY-MM-DD HH:mm:ss"); // '2024-01-01 12:00:00'
// 格式化时间戳
formatDate(1704038400000, "YYYY-MM-DD"); // '2024-01-01'
```
### formatNumber
数字格式化。
```typescript
import { formatNumber } from "@venus/utils";
// 千分位
formatNumber(1234567.89); // '1,234,567.89'
// 保留小数位
formatNumber(123.456, 2); // '123.46'
// 货币格式
formatNumber(1234.5, 2, "¥"); // '¥1,234.50'
```
### formatBytes
字节格式化。
```typescript
import { formatBytes } from "@venus/utils";
formatBytes(1024); // '1 KB'
formatBytes(1048576); // '1 MB'
formatBytes(1073741824); // '1 GB'
```
### truncate
字符串截断。
```typescript
import { truncate } from "@venus/utils";
truncate("这是一段很长的文本", 10); // '这是一段很长的...'
truncate("这是一段很长的文本", 10, "***"); // '这是一段很长的***'
```
## 数组工具
### unique
数组去重。
```typescript
import { unique } from "@venus/utils";
unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
// 对象数组去重
unique(
[
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 1, name: "a" },
],
"id",
); // [{ id: 1, name: 'a' }, { id: 2, name: 'b' }]
```
### groupBy
数组分组。
```typescript
import { groupBy } from "@venus/utils";
const users = [
{ id: 1, role: "admin" },
{ id: 2, role: "user" },
{ id: 3, role: "admin" },
];
groupBy(users, "role");
// {
// admin: [{ id: 1, role: 'admin' }, { id: 3, role: 'admin' }],
// user: [{ id: 2, role: 'user' }]
// }
```
### chunk
数组分块。
```typescript
import { chunk } from "@venus/utils";
chunk([1, 2, 3, 4, 5, 6], 2);
// [[1, 2], [3, 4], [5, 6]]
```
### shuffle
数组打乱。
```typescript
import { shuffle } from "@venus/utils";
shuffle([1, 2, 3, 4, 5]); // [3, 1, 5, 2, 4]
```
## 对象工具
### pick
选取对象属性。
```typescript
import { pick } from "@venus/utils";
const obj = { a: 1, b: 2, c: 3 };
pick(obj, ["a", "b"]); // { a: 1, b: 2 }
```
### omit
排除对象属性。
```typescript
import { omit } from "@venus/utils";
const obj = { a: 1, b: 2, c: 3 };
omit(obj, ["a"]); // { b: 2, c: 3 }
```
### get
安全获取对象属性。
```typescript
import { get } from "@venus/utils";
const obj = { a: { b: { c: 1 } } };
get(obj, "a.b.c"); // 1
get(obj, "a.b.d"); // undefined
get(obj, "a.b.d", "default"); // 'default'
```
### set
安全设置对象属性。
```typescript
import { set } from "@venus/utils";
const obj = {};
set(obj, "a.b.c", 1); // { a: { b: { c: 1 } } }
```
## URL 工具
### parseQuery
解析 URL 查询参数。
```typescript
import { parseQuery } from "@venus/utils";
parseQuery("?a=1&b=2"); // { a: '1', b: '2' }
parseQuery("a=1&b=2"); // { a: '1', b: '2' }
```
### stringifyQuery
序列化查询参数。
```typescript
import { stringifyQuery } from "@venus/utils";
stringifyQuery({ a: 1, b: 2 }); // 'a=1&b=2'
```
### getUrlParam
获取 URL 参数。
```typescript
import { getUrlParam } from "@venus/utils";
// 当前 URL: https://example.com?name=test&id=123
getUrlParam("name"); // 'test'
getUrlParam("id"); // '123'
```
## 加密工具
### md5
MD5 加密。
```typescript
import { md5 } from "@venus/utils";
md5("hello"); // '5d41402abc4b2a76b9719d911017c592'
```
### base64Encode
Base64 编码。
```typescript
import { base64Encode } from "@venus/utils";
base64Encode("hello"); // 'aGVsbG8='
```
### base64Decode
Base64 解码。
```typescript
import { base64Decode } from "@venus/utils";
base64Decode("aGVsbG8="); // 'hello'
```
## 存储工具
### storage
本地存储封装。
```typescript
import { storage } from "@venus/utils";
// 保存数据
storage.set("key", "value");
storage.set("user", { name: "admin" });
// 获取数据
storage.get("key"); // 'value'
storage.get("user"); // { name: 'admin' }
// 删除数据
storage.remove("key");
// 清空数据
storage.clear();
// SessionStorage
storage.session.set("key", "value");
storage.session.get("key");
```
## 防抖节流
### debounce
防抖。
```typescript
import { debounce } from "@venus/utils";
const fn = debounce(() => {
console.log("执行");
}, 300);
// 多次调用,只执行最后一次
fn();
fn();
fn();
```
### throttle
节流。
```typescript
import { throttle } from "@venus/utils";
const fn = throttle(() => {
console.log("执行");
}, 300);
// 多次调用,每 300ms 执行一次
fn();
fn();
fn();
```
## 文件工具
### downloadFile
下载文件。
```typescript
import { downloadFile } from "@venus/utils";
// 下载 Blob
downloadFile(blob, "filename.pdf");
// 下载 URL
downloadFile("https://example.com/file.pdf", "filename.pdf");
```
### uploadFile
上传文件。
```typescript
import { uploadFile } from "@venus/utils";
const file = event.target.files[0];
const result = await uploadFile("/api/upload", file, {
onProgress: (percent) => {
console.log(`上传进度: ${percent}%`);
},
});
```
## 树形数据工具
### listToTree
列表转树形。
```typescript
import { listToTree } from "@venus/utils";
const list = [
{ id: 1, parentId: 0, name: "a" },
{ id: 2, parentId: 1, name: "b" },
{ id: 3, parentId: 1, name: "c" },
];
listToTree(list, {
id: "id",
parentId: "parentId",
children: "children",
});
// [
// {
// id: 1,
// parentId: 0,
// name: 'a',
// children: [
// { id: 2, parentId: 1, name: 'b' },
// { id: 3, parentId: 1, name: 'c' },
// ],
// },
// ]
```
### treeToList
树形转列表。
```typescript
import { treeToList } from "@venus/utils";
const tree = [
{
id: 1,
children: [{ id: 2 }, { id: 3 }],
},
];
treeToList(tree); // [{ id: 1 }, { id: 2 }, { id: 3 }]
```
# 更新日志
## v5.5.9 (2024-11-09)
### ✨ Features
- 新增文档站点
- 完善项目配置
- 优化构建流程
### 🐛 Bug Fixes
- 修复路由权限问题
- 修复表格分页bug
- 修复主题切换闪烁
### 🎨 Styles
- 优化界面样式
- 调整组件间距
### 📝 Documentation
- 更新使用文档
- 新增API文档
- 完善组件文档
## v5.5.0 (2024-10-01)
### ✨ Features
- 支持 Vue 3.5
- 新增国际化支持
- 新增主题定制功能
- 新增暗黑模式
### 🐛 Bug Fixes
- 修复登录失效问题
- 修复菜单折叠动画
### ⚡ Performance
- 优化首屏加载速度
- 优化打包体积
## v5.4.0 (2024-08-15)
### ✨ Features
- 新增 Naive UI 版本
- 新增表单设计器
- 新增图表组件
### 🐛 Bug Fixes
- 修复权限控制问题
- 修复表格排序bug
## v5.3.0 (2024-07-01)
### ✨ Features
- 支持 pnpm 9.0
- 新增 Mock 服务
- 新增文件上传组件
### 📝 Documentation
- 更新快速开始文档
## v5.2.0 (2024-06-01)
### ✨ Features
- 新增 Element Plus 版本
- 优化路由配置
- 新增权限指令
### 🐛 Bug Fixes
- 修复侧边栏菜单问题
## v5.1.0 (2024-05-01)
### ✨ Features
- 支持 Vite 5
- 优化构建配置
- 新增组件库
### ⚡ Performance
- 优化页面加载速度
## v5.0.0 (2024-04-01)
### ✨ Features
- 全新 monorepo 架构
- 支持多 UI 框架
- 完整的 TypeScript 支持
- 现代化的开发体验
### 🎉 Initial Release
首个正式版本发布!
## v1.0.0 (2025-12-10)
- 基本框架划分/基础设施搭建/完成基础库初版
- 第三方依赖及本地依赖管理配置
- 代码检查/代码格式化配置
- 微前端模版(基座/子应用)
- 项目构建流程优化配置
- 部署上线流程优化配置
- 微前端智能体平台开发/上线
# 图表组件
基于 ECharts 封装的图表组件。
## 基础用法
```vue
<template>
<Chart :option="chartOption" :height="400" />
</template>
<script setup lang="ts">
import { ref } from "vue";
const chartOption = ref({
title: {
text: "销售数据",
},
tooltip: {},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
});
</script>
```
## 折线图
```typescript
const lineOption = {
title: {
text: "趋势图",
},
tooltip: {
trigger: "axis",
},
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
name: "销量",
type: "line",
data: [150, 230, 224, 218, 135, 147, 260],
smooth: true,
},
],
};
```
## 饼图
```typescript
const pieOption = {
title: {
text: "数据分布",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "访问来源",
type: "pie",
radius: "50%",
data: [
{ value: 1048, name: "搜索引擎" },
{ value: 735, name: "直接访问" },
{ value: 580, name: "邮件营销" },
{ value: 484, name: "联盟广告" },
{ value: 300, name: "视频广告" },
],
},
],
};
```
## 响应式图表
```vue
<template>
<Chart :option="chartOption" :height="400" auto-resize />
</template>
```
## 动态数据更新
```vue
<script setup lang="ts">
import { ref, onMounted } from "vue";
const chartOption = ref({
xAxis: {
type: "category",
data: [],
},
yAxis: {
type: "value",
},
series: [
{
type: "line",
data: [],
},
],
});
// 模拟数据更新
onMounted(() => {
setInterval(() => {
const newData = Math.random() * 100;
chartOption.value.series[0].data.push(newData);
chartOption.value.xAxis.data.push(new Date().toLocaleTimeString());
// 保持最新的 20 个数据点
if (chartOption.value.series[0].data.length > 20) {
chartOption.value.series[0].data.shift();
chartOption.value.xAxis.data.shift();
}
}, 1000);
});
</script>
```
## API
### Props
| 属性 | 说明 | 类型 | 默认值 |
| ---------- | ---------------- | ------------------ | -------- |
| option | 图表配置 | `EChartsOption` | - |
| width | 宽度 | `string \| number` | `'100%'` |
| height | 高度 | `string \| number` | `400` |
| autoResize | 自动响应尺寸变化 | `boolean` | `true` |
| loading | 加载状态 | `boolean` | `false` |
| theme | 主题 | `string \| object` | - |
### Events
| 事件名 | 说明 | 参数 |
| ------ | -------------- | -------------------- |
| ready | 图表初始化完成 | `(instance) => void` |
| click | 点击事件 | `(params) => void` |
### Methods
| 方法名 | 说明 | 参数 |
| ----------- | ----------------- | ----------------------- |
| getInstance | 获取 ECharts 实例 | `() => EChartsInstance` |
| resize | 手动调整大小 | `() => void` |
| clear | 清空图表 | `() => void` |
## 常用图表示例
### 柱状图
```typescript
const barOption = {
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
type: "bar",
data: [120, 200, 150, 80, 70, 110, 130],
},
],
};
```
### 散点图
```typescript
const scatterOption = {
xAxis: {},
yAxis: {},
series: [
{
type: "scatter",
data: [
[10, 20],
[30, 40],
[50, 60],
],
},
],
};
```
### 雷达图
```typescript
const radarOption = {
radar: {
indicator: [
{ name: "销售", max: 100 },
{ name: "管理", max: 100 },
{ name: "技术", max: 100 },
{ name: "客服", max: 100 },
{ name: "研发", max: 100 },
],
},
series: [
{
type: "radar",
data: [
{
value: [80, 90, 85, 75, 95],
name: "评分",
},
],
},
],
};
```
# 表单组件
强大的表单组件,支持动态表单配置、表单验证、联动等功能。
## 基础用法
```vue
<template>
<Form v-model="formData" :schema="formSchema" @submit="handleSubmit" />
</template>
<script setup lang="ts">
import { ref } from "vue";
const formData = ref({
username: "",
email: "",
age: null,
});
const formSchema = [
{
field: "username",
label: "用户名",
component: "Input",
required: true,
rules: [
{ required: true, message: "请输入用户名" },
{ min: 3, max: 20, message: "用户名长度在 3 到 20 个字符" },
],
},
{
field: "email",
label: "邮箱",
component: "Input",
required: true,
rules: [
{ required: true, message: "请输入邮箱" },
{ type: "email", message: "请输入正确的邮箱地址" },
],
},
{
field: "age",
label: "年龄",
component: "InputNumber",
componentProps: {
min: 1,
max: 150,
},
},
];
const handleSubmit = (values) => {
console.log("表单数据:", values);
};
</script>
```
## 表单配置
### Schema 配置项
| 属性 | 说明 | 类型 | 默认值 |
| -------------- | -------- | ---------------------------------- | ------- |
| field | 字段名 | `string` | - |
| label | 标签 | `string` | - |
| component | 组件类型 | `string` | - |
| required | 是否必填 | `boolean` | `false` |
| rules | 验证规则 | `Rule[]` | - |
| componentProps | 组件属性 | `object` | - |
| defaultValue | 默认值 | `any` | - |
| show | 是否显示 | `boolean \| (formData) => boolean` | `true` |
| disabled | 是否禁用 | `boolean \| (formData) => boolean` | `false` |
## 表单验证
### 内置验证规则
```typescript
const rules = [
// 必填
{ required: true, message: "请输入" },
// 类型验证
{ type: "email", message: "请输入正确的邮箱" },
{ type: "url", message: "请输入正确的 URL" },
{ type: "number", message: "请输入数字" },
// 长度验证
{ min: 3, message: "最少 3 个字符" },
{ max: 20, message: "最多 20 个字符" },
{ len: 11, message: "长度必须为 11 个字符" },
// 正则验证
{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
// 自定义验证
{
validator: (rule, value) => {
return value > 18;
},
message: "年龄必须大于 18",
},
];
```
## 动态表单
### 表单联动
```typescript
const formSchema = [
{
field: "type",
label: "类型",
component: "Select",
componentProps: {
options: [
{ label: "个人", value: "personal" },
{ label: "企业", value: "company" },
],
},
},
{
field: "idCard",
label: "身份证号",
component: "Input",
// 当类型为个人时显示
show: (formData) => formData.type === "personal",
},
{
field: "businessLicense",
label: "营业执照",
component: "Input",
// 当类型为企业时显示
show: (formData) => formData.type === "company",
},
];
```
## 常用组件
### Input 输入框
```typescript
{
field: 'name',
label: '姓名',
component: 'Input',
componentProps: {
placeholder: '请输入姓名',
maxlength: 20,
showCount: true,
},
}
```
### Select 下拉选择
```typescript
{
field: 'city',
label: '城市',
component: 'Select',
componentProps: {
options: [
{ label: '北京', value: 'beijing' },
{ label: '上海', value: 'shanghai' },
],
placeholder: '请选择城市',
},
}
```
### DatePicker 日期选择
```typescript
{
field: 'birthday',
label: '生日',
component: 'DatePicker',
componentProps: {
format: 'YYYY-MM-DD',
valueFormat: 'YYYY-MM-DD',
},
}
```
## API
### Props
| 属性 | 说明 | 类型 | 默认值 |
| ---------- | -------- | ---------------------------------------- | -------------- |
| modelValue | 表单数据 | `object` | - |
| schema | 表单配置 | `FormSchema[]` | - |
| labelWidth | 标签宽度 | `number \| string` | `'100px'` |
| layout | 布局方式 | `'horizontal' \| 'vertical' \| 'inline'` | `'horizontal'` |
### Events
| 事件名 | 说明 | 参数 |
| ------------ | ---------- | ------------------------------------ |
| submit | 提交表单 | `(values: object) => void` |
| reset | 重置表单 | `() => void` |
| valuesChange | 表单值变化 | `(changedValues, allValues) => void` |
### Methods
| 方法名 | 说明 | 参数 |
| ------------- | ---------- | ------------------------------------- |
| validate | 验证表单 | `() => Promise<any>` |
| resetFields | 重置表单 | `() => void` |
| setFieldValue | 设置字段值 | `(field: string, value: any) => void` |
| getFieldValue | 获取字段值 | `(field: string) => any` |
# 弹窗组件
模态对话框组件。
## 基础用法
```vue
<template>
<Button @click="visible = true">打开弹窗</Button>
<Modal v-model:visible="visible" title="弹窗标题" @ok="handleOk" @cancel="handleCancel">
<p>弹窗内容</p>
</Modal>
</template>
<script setup lang="ts">
import { ref } from "vue";
const visible = ref(false);
const handleOk = () => {
visible.value = false;
};
const handleCancel = () => {
visible.value = false;
};
</script>
```
## 异步关闭
```vue
<script setup lang="ts">
const loading = ref(false);
const handleOk = async () => {
loading.value = true;
try {
await someAsyncOperation();
visible.value = false;
} finally {
loading.value = false;
}
};
</script>
<template>
<Modal v-model:visible="visible" :confirm-loading="loading" @ok="handleOk">
<p>内容</p>
</Modal>
</template>
```
## 自定义页脚
```vue
<template>
<Modal v-model:visible="visible" title="自定义页脚">
<p>弹窗内容</p>
<template #footer>
<Button @click="visible = false">取消</Button>
<Button type="primary" @click="handleSubmit">提交</Button>
<Button type="danger" @click="handleDelete">删除</Button>
</template>
</Modal>
</template>
```
## 表单弹窗
```vue
<template>
<Modal v-model:visible="visible" title="编辑用户" @ok="handleSubmit">
<Form ref="formRef" v-model="formData" :schema="formSchema" />
</Modal>
</template>
<script setup lang="ts">
import { ref } from "vue";
const visible = ref(false);
const formRef = ref();
const formData = ref({});
const formSchema = [
{
field: "name",
label: "姓名",
component: "Input",
required: true,
},
];
const handleSubmit = async () => {
try {
const values = await formRef.value.validate();
await saveUser(values);
visible.value = false;
} catch (error) {
console.error("验证失败", error);
}
};
</script>
```
## 函数式调用
### 确认对话框
```typescript
import { Modal } from "@/components";
Modal.confirm({
title: "确认删除?",
content: "删除后无法恢复",
onOk: async () => {
await deleteItem();
},
});
```
### 信息提示
```typescript
// 成功
Modal.success({
title: "操作成功",
content: "数据已保存",
});
// 错误
Modal.error({
title: "操作失败",
content: "网络错误,请重试",
});
// 警告
Modal.warning({
title: "警告",
content: "请注意数据安全",
});
// 信息
Modal.info({
title: "提示",
content: "这是一条提示信息",
});
```
## 全屏弹窗
```vue
<template>
<Modal v-model:visible="visible" title="全屏弹窗" :fullscreen="true">
<p>全屏内容</p>
</Modal>
</template>
```
## 可拖拽弹窗
```vue
<template>
<Modal v-model:visible="visible" title="可拖拽弹窗" draggable>
<p>可以拖拽标题栏移动弹窗</p>
</Modal>
</template>
```
## API
### Props
| 属性 | 说明 | 类型 | 默认值 |
| -------------- | --------------------- | ------------------ | -------- |
| visible | 是否显示 | `boolean` | `false` |
| title | 标题 | `string` | - |
| width | 宽度 | `string \| number` | `520` |
| confirmLoading | 确认按钮加载状态 | `boolean` | `false` |
| okText | 确认按钮文字 | `string` | `'确定'` |
| cancelText | 取消按钮文字 | `string` | `'取消'` |
| maskClosable | 点击遮罩是否关闭 | `boolean` | `true` |
| keyboard | 是否支持键盘 ESC 关闭 | `boolean` | `true` |
| fullscreen | 是否全屏 | `boolean` | `false` |
| draggable | 是否可拖拽 | `boolean` | `false` |
### Events
| 事件名 | 说明 | 参数 |
| ---------- | -------------- | ------------ |
| ok | 点击确定按钮 | `() => void` |
| cancel | 点击取消按钮 | `() => void` |
| afterClose | 完全关闭后触发 | `() => void` |
### Slots
| 插槽名 | 说明 |
| ------- | ---- |
| default | 内容 |
| title | 标题 |
| footer | 页脚 |
### 函数式 API
```typescript
interface ModalOptions {
title?: string;
content?: string;
okText?: string;
cancelText?: string;
onOk?: () => void | Promise<void>;
onCancel?: () => void;
}
Modal.confirm(options: ModalOptions): void;
Modal.success(options: ModalOptions): void;
Modal.error(options: ModalOptions): void;
Modal.warning(options: ModalOptions): void;
Modal.info(options: ModalOptions): void;
```
# 组件总览
Venus Admin 提供了丰富的业务组件,帮助快速构建企业级应用。
## 基础组件
### Button 按钮
常用的操作按钮。
```vue
<template>
<Button type="primary">主要按钮</Button>
<Button type="default">默认按钮</Button>
<Button type="danger">危险按钮</Button>
</template>
```
### Card 卡片
通用卡片容器。
```vue
<template>
<Card title="卡片标题">
<p>卡片内容</p>
</Card>
</template>
```
## 表单组件
### Form 表单
详见 [表单组件](/components/form)
### Input 输入框
基础的输入框组件。
### Select 选择器
下拉选择器。
### DatePicker 日期选择器
日期选择组件。
## 数据展示
### Table 表格
功能强大的数据表格组件。
详见 [表格组件](/components/table)
### Tree 树形控件
树形数据展示。
### List 列表
通用列表组件。
## 反馈组件
### Modal 弹窗
详见 [弹窗组件](/components/modal)
### Message 消息提示
全局消息提示。
```typescript
import { message } from "@/utils/message";
message.success("操作成功");
message.error("操作失败");
message.warning("警告信息");
message.info("提示信息");
```
### Notification 通知
全局通知。
### Loading 加载中
加载中状态。
## 布局组件
### Layout 布局
页面整体布局。
### Header 页头
顶部导航条。
### Sidebar 侧边栏
侧边导航菜单。
### Footer 页脚
页面底部。
## 业务组件
### Page 页面容器
标准页面容器组件。
```vue
<template>
<Page title="页面标题">
<template #extra>
<Button>操作按钮</Button>
</template>
<!-- 页面内容 -->
<div>内容区域</div>
</Page>
</template>
```
### Search 查询表单
表格查询表单。
```vue
<template>
<Search v-model="searchForm" :schema="searchSchema" @search="handleSearch" @reset="handleReset" />
</template>
```
### Ellipsis 文本省略
文本溢出省略。
```vue
<template>
<Ellipsis :length="50" :tooltip="true">这是一段很长的文本内容...</Ellipsis>
</template>
```
### Icon 图标
图标组件,支持 Iconify。
```vue
<template>
<Icon icon="lucide:home" />
<Icon icon="mdi:account" :size="24" />
</template>
```
## 高级组件
### Upload 上传
文件上传组件。
```vue
<template>
<Upload v-model="fileList" action="/api/upload" :max-count="5" @success="handleSuccess" />
</template>
```
### Editor 编辑器
富文本编辑器。
### CodeEditor 代码编辑器
代码编辑器组件。
### Chart 图表
图表组件。
详见 [图表组件](/components/chart)
## 下一步
- [表单组件](/components/form)
- [表格组件](/components/table)
- [弹窗组件](/components/modal)
- [图表组件](/components/chart)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!