Commit 9949661e by Lin

feat: 测试验证平台/公共UI组件库配置优化

1 parent 6262c079
Showing 62 changed files with 1636 additions and 1420 deletions
// 此文件由 auto-routes 插件自动生成,请勿手动编辑 // 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules // 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: 2026/1/22 14:01:32 // 生成时间: 2026/1/22 14:14:23
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
...@@ -82,20 +82,6 @@ export const autoRoutes: RouteRecordRaw[] = [ ...@@ -82,20 +82,6 @@ export const autoRoutes: RouteRecordRaw[] = [
], ],
}, },
{ {
path: "/test/index",
id: "test",
title: "Test",
icon: "",
level: 0,
hidden: false,
meta: {
"authority": "test",
"keepAlive": false,
"requiresAuth": false,
"title": "Test"
},
},
{
path: "/communication", path: "/communication",
id: ".-communication", id: ".-communication",
title: "Communication", title: "Communication",
......
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
<!DOCTYPE html>
<html lang="zh-CN" style="--el-color-primary: #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>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "@venus/example-admin",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@element-plus/icons-vue": "catalog:",
"@venus/common-ui-vue": "workspace:*",
"@vueuse/core": "catalog:",
"element-plus": "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:",
"vue-tsc": "catalog:"
}
}
<script setup lang="ts"></script>
<template>
<div id="main-app">
<router-view />
</div>
</template>
<style scoped>
#main-app {
width: 100%;
height: 100%;
min-height: 100vh;
}
</style>
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
export {}
declare global {
const EffectScope: typeof import('vue')['EffectScope']
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const createPinia: typeof import('pinia')['createPinia']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const effectScope: typeof import('vue')['effectScope']
const getActivePinia: typeof import('pinia')['getActivePinia']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const mapActions: typeof import('pinia')['mapActions']
const mapGetters: typeof import('pinia')['mapGetters']
const mapState: typeof import('pinia')['mapState']
const mapStores: typeof import('pinia')['mapStores']
const mapWritableState: typeof import('pinia')['mapWritableState']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeRouteLeave: typeof import('vue-router')['onBeforeRouteLeave']
const onBeforeRouteUpdate: typeof import('vue-router')['onBeforeRouteUpdate']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const reactive: typeof import('vue')['reactive']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const setActivePinia: typeof import('pinia')['setActivePinia']
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const storeToRefs: typeof import('pinia')['storeToRefs']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useId: typeof import('vue')['useId']
const useLink: typeof import('vue-router')['useLink']
const useModel: typeof import('vue')['useModel']
const useRoute: typeof import('vue-router')['useRoute']
const useRouter: typeof import('vue-router')['useRouter']
const useSlots: typeof import('vue')['useSlots']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
declare module 'vue' {
export interface GlobalComponents {
ElButton: typeof import('element-plus/es')['ElButton']
ElForm: typeof import('element-plus/es')['ElForm']
ElFormItem: typeof import('element-plus/es')['ElFormItem']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElInput: typeof import('element-plus/es')['ElInput']
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
ElTable: typeof import('element-plus/es')['ElTable']
ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
ElTree: typeof import('element-plus/es')['ElTree']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
}
import type { MenuItem, TopMenuItem } from '@/types/menu';
// 硬编码的菜单配置
export const homeMenus: MenuItem[] = [
{
id: 'home-dashboard',
title: '工作台',
path: '/home/dashboard',
level: 1,
},
];
export const systemMenus: MenuItem[] = [
{
id: 'system-user',
title: 'UI组件库',
path: '/system/user',
level: 1,
},
{
id: 'system-role',
title: '角色管理',
path: '/system/role',
level: 1,
},
{
id: 'system-menu',
title: '菜单管理',
path: '/system/menu',
level: 1,
},
];
export const businessMenus: MenuItem[] = [
{
id: 'business-order',
title: '订单管理',
path: '/business/order',
level: 1,
children: [
{
id: 'business-order-list',
title: '订单列表',
path: '/business/order/list',
level: 2,
parentId: 'business-order',
},
{
id: 'business-order-detail',
title: '订单详情',
path: '/business/order/detail',
level: 2,
parentId: 'business-order',
},
],
},
{
id: 'business-product',
title: '产品管理',
path: '/business/product',
level: 1,
children: [
{
id: 'business-product-list',
title: '产品列表',
path: '/business/product/list',
level: 2,
parentId: 'business-product',
},
{
id: 'business-product-add',
title: '添加产品',
path: '/business/product/add',
level: 2,
parentId: 'business-product',
},
],
},
];
export const defaultTopMenus: TopMenuItem[] = [
{
id: 'home',
title: '首页',
path: '/home',
sidebarMenus: homeMenus,
},
{
id: 'system',
title: '系统管理',
path: '/system',
sidebarMenus: systemMenus,
},
{
id: 'business',
title: '业务管理',
path: '/business',
sidebarMenus: businessMenus,
},
];
export function getSidebarMenusByPath(path: string): MenuItem[] {
const topMenu = defaultTopMenus.find((menu) => path.startsWith(menu.path));
return topMenu?.sidebarMenus || [];
}
export function findMenuItem(menus: MenuItem[], id: string): MenuItem | null {
for (const menu of menus) {
if (menu.id === id) {
return menu;
}
if (menu.children) {
const found = findMenuItem(menu.children, id);
if (found) return found;
}
}
return null;
}
export function isPathMatch(menuPath: string, targetPath: string): boolean {
if (!menuPath || !targetPath) {
return false;
}
const normalizedMenuPath = menuPath.replace(/\/+$/, '');
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
if (normalizedMenuPath === normalizedTargetPath) {
return true;
}
if (normalizedMenuPath.includes(':')) {
const pattern = normalizedMenuPath
.replace(/:[^/]+/g, '[^/]+')
.replace(/\//g, '\\/');
const regex = new RegExp(`^${pattern}$`);
return regex.test(normalizedTargetPath);
}
if (normalizedTargetPath.startsWith(normalizedMenuPath)) {
const nextChar = normalizedTargetPath[normalizedMenuPath.length];
if (nextChar === '/' || nextChar === undefined) {
return true;
}
}
return false;
}
export function getMenuParentPaths(
menus: MenuItem[],
targetPath: string,
): string[] {
const paths: string[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
function findPathChain(
items: MenuItem[],
target: string,
currentPathChain: string[],
): boolean {
for (const item of items) {
const newPathChain = [...currentPathChain, item.path];
if (isPathMatch(item.path, target)) {
paths.push(...newPathChain);
return true;
}
if (item.children && item.children.length > 0) {
if (findPathChain(item.children, target, newPathChain)) {
return true;
}
}
}
return false;
}
findPathChain(menus, normalizedTargetPath, []);
return Array.from(new Set(paths));
}
export function getMenuChain(
menus: MenuItem[],
targetPath: string,
): MenuItem[] {
const menuChain: MenuItem[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
function findMenuChain(
items: MenuItem[],
target: string,
currentChain: MenuItem[],
): boolean {
for (const item of items) {
const newChain = [...currentChain, item];
if (isPathMatch(item.path, target)) {
menuChain.push(...newChain);
return true;
}
if (item.children && item.children.length > 0) {
if (findMenuChain(item.children, target, newChain)) {
return true;
}
}
}
return false;
}
findMenuChain(menus, normalizedTargetPath, []);
return menuChain;
}
<script setup lang="ts">
import type { BreadcrumbItem } from '@/types/menu';
import { useRouter } from 'vue-router';
defineProps<{
breadcrumbs: BreadcrumbItem[];
}>();
const router = useRouter();
const handleBreadcrumbClick = (
crumb: BreadcrumbItem,
index: number,
breadcrumbs: BreadcrumbItem[],
) => {
if (crumb.path && index < breadcrumbs.length - 1) {
router.push(crumb.path);
}
};
</script>
<template>
<div v-if="breadcrumbs.length > 0" class="breadcrumb">
<template v-for="(crumb, index) in breadcrumbs" :key="index">
<span
class="breadcrumb-item"
:class="{
clickable: crumb.path && index < breadcrumbs.length - 1,
}"
@click="handleBreadcrumbClick(crumb, index, breadcrumbs)"
>
{{ crumb.title }}
</span>
<span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator"
>/</span
>
</template>
</div>
</template>
<style scoped>
.breadcrumb {
display: flex;
flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
font-size: 12px;
color: #2f3133;
}
.breadcrumb-item {
color: #2f3133;
}
.breadcrumb-item.clickable {
color: #969aa3;
cursor: pointer;
transition: color 0.3s;
}
.breadcrumb-item.clickable:hover {
color: #2f3133;
}
.breadcrumb-separator {
margin: 0 8px;
color: #999;
}
</style>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
const showDropdown = ref(false);
const userInfo = {
name: '管理员',
avatar: '👤',
id: '001',
};
const userInitial = '管';
const toggleDropdown = () => {
showDropdown.value = !showDropdown.value;
};
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (!target.closest('.user-info')) {
showDropdown.value = false;
}
};
const handleProfile = () => {
showDropdown.value = false;
};
const handleSettings = () => {
showDropdown.value = false;
};
onMounted(() => {
document.addEventListener('click', handleClickOutside);
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
</script>
<template>
<div class="user-info">
<div class="user-info-card" @click.stop="toggleDropdown">
<div class="avatar">{{ userInitial }}</div>
<p class="name">{{ userInfo.name }}</p>
</div>
<div v-if="showDropdown" class="user-dropdown" @click.stop>
<div class="dropdown-header">
<div class="dropdown-avatar">{{ userInfo.avatar }}</div>
<div class="dropdown-info">
<div class="dropdown-name">{{ userInfo.name }}</div>
<div class="dropdown-id">ID: {{ userInfo.id }}</div>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="dropdown-menu">
<div class="menu-item" @click="handleProfile">
<span class="menu-icon">👤</span>
<span>个人中心</span>
</div>
<div class="menu-item" @click="handleSettings">
<span class="menu-icon">⚙️</span>
<span>设置</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.user-info {
position: relative;
padding: 8px;
}
.user-info-card {
position: relative;
display: flex;
gap: 6px;
align-items: center;
justify-content: center;
padding: 8px 12px;
cursor: pointer;
border-radius: 6px;
transition: all 0.2s;
}
.user-info-card:hover {
background: rgb(0 0 0 / 4%);
}
.user-info-card .avatar {
flex-shrink: 0;
width: 28px;
height: 28px;
font-size: 16px;
font-weight: bold;
line-height: 28px;
color: #1956fe;
text-align: center;
background: #e6efff;
border-radius: 50%;
opacity: 1;
}
.user-info-card .name {
font-size: 12px;
color: #777c85;
white-space: nowrap;
}
.user-dropdown {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 1000;
min-width: 280px;
overflow: hidden;
background: white;
border-radius: 8px;
box-shadow: 0 8px 24px rgb(0 0 0 / 15%);
}
.dropdown-header {
display: flex;
gap: 12px;
align-items: center;
padding: 16px;
}
.dropdown-avatar {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
font-size: 32px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
}
.dropdown-info {
flex: 1;
min-width: 0;
}
.dropdown-name {
margin-bottom: 4px;
overflow: hidden;
text-overflow: ellipsis;
font-size: 18px;
font-weight: 600;
color: #262626;
white-space: nowrap;
}
.dropdown-id {
font-size: 13px;
color: #8c8c8c;
}
.dropdown-divider {
height: 1px;
margin: 0 8px;
background: #f0f0f0;
}
.dropdown-menu {
padding: 8px;
}
.menu-item {
display: flex;
gap: 12px;
align-items: center;
padding: 12px 16px;
font-size: 14px;
color: #262626;
cursor: pointer;
border-radius: 6px;
transition: all 0.2s;
}
.menu-item:hover {
color: #667eea;
background: #f5f5f5;
}
.menu-icon {
font-size: 18px;
}
</style>
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import { useAppStore } from './stores';
import CommonUI from '@venus/common-ui-vue';
import './styles/element/index.scss';
import 'element-plus/dist/index.css';
import './style.css';
const app = createApp(App);
const pinia = createPinia();
// 注册通用 UI 组件库
app.use(CommonUI);
app.use(pinia);
app.use(router);
// 初始化应用
const appStore = useAppStore();
appStore.initApp();
app.mount('#app');
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Layout',
component: () => import('@/layouts/BasicLayout.vue'),
redirect: '/home',
children: [
{
path: '/home',
name: 'Home',
component: () => import('@/views/Home.vue'),
redirect: '/home/dashboard',
meta: {
title: '首页',
},
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: {
title: '工作台',
},
},
],
},
{
path: '/system/user',
name: 'SystemUser',
component: () => import('@/views/system/User.vue'),
meta: {
title: 'UI组件库',
},
},
{
path: '/system/role',
name: 'SystemRole',
component: () => import('@/views/system/Role.vue'),
meta: {
title: '角色管理',
},
},
{
path: '/system/menu',
name: 'SystemMenu',
component: () => import('@/views/system/Menu.vue'),
meta: {
title: '菜单管理',
},
},
{
path: '/business/order/list',
name: 'BusinessOrderList',
component: () => import('@/views/business/OrderList.vue'),
meta: {
title: '订单列表',
},
},
{
path: '/business/order/detail',
name: 'BusinessOrderDetail',
component: () => import('@/views/business/OrderDetail.vue'),
meta: {
title: '订单详情',
},
},
{
path: '/business/product/list',
name: 'BusinessProductList',
component: () => import('@/views/business/ProductList.vue'),
meta: {
title: '产品列表',
},
},
{
path: '/business/product/add',
name: 'BusinessProductAdd',
component: () => import('@/views/business/ProductAdd.vue'),
meta: {
title: '添加产品',
},
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
meta: {
title: '404',
},
},
],
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to: any, _from: any, next: any) => {
document.title = to.meta.title
? `${to.meta.title} - 后台管理系统`
: '后台管理系统';
next();
});
export default router;
import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
export const useAppStore = defineStore('app', () => {
const sidebarCollapsed = ref(false);
const theme = ref<'dark' | 'light'>('light');
const loading = ref(false);
const device = ref<'desktop' | 'mobile'>('desktop');
const language = ref('zh-CN');
const isMobile = computed(() => device.value === 'mobile');
const isDark = computed(() => theme.value === 'dark');
const toggleSidebar = () => {
sidebarCollapsed.value = !sidebarCollapsed.value;
};
const setSidebarCollapsed = (collapsed: boolean) => {
sidebarCollapsed.value = collapsed;
};
const toggleTheme = () => {
theme.value = theme.value === 'light' ? 'dark' : 'light';
document.documentElement.dataset.theme = theme.value;
};
const setTheme = (newTheme: 'dark' | 'light') => {
theme.value = newTheme;
document.documentElement.dataset.theme = newTheme;
};
const setLoading = (isLoading: boolean) => {
loading.value = isLoading;
};
const setDevice = (deviceType: 'desktop' | 'mobile') => {
device.value = deviceType;
};
const setLanguage = (lang: string) => {
language.value = lang;
};
const initApp = () => {
const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null;
if (savedTheme) {
setTheme(savedTheme);
}
const savedSidebarState = localStorage.getItem('sidebarCollapsed');
if (savedSidebarState !== null) {
sidebarCollapsed.value = savedSidebarState === 'true';
}
const checkDevice = () => {
const width = window.innerWidth;
setDevice(width < 768 ? 'mobile' : 'desktop');
};
checkDevice();
window.addEventListener('resize', checkDevice);
};
const saveAppState = () => {
localStorage.setItem('theme', theme.value);
localStorage.setItem('sidebarCollapsed', String(sidebarCollapsed.value));
};
return {
sidebarCollapsed,
theme,
loading,
device,
language,
isMobile,
isDark,
toggleSidebar,
setSidebarCollapsed,
toggleTheme,
setTheme,
setLoading,
setDevice,
setLanguage,
initApp,
saveAppState,
};
});
export { useAppStore } from './app';
export { useMenuStore } from './menu';
import type { MenuItem, TopMenuItem } from '@/types/menu';
import { ref } from 'vue';
import { defineStore } from 'pinia';
import { defaultTopMenus } from '@/config/menus';
export const useMenuStore = defineStore('menu', () => {
const topMenus = ref<TopMenuItem[]>(defaultTopMenus);
const isMenusLoaded = ref(true);
const setTopMenus = (menus: TopMenuItem[]) => {
topMenus.value = menus;
isMenusLoaded.value = true;
};
const getSidebarMenusByPath = (path: string): MenuItem[] => {
const topMenu = topMenus.value.find((menu) => path.startsWith(menu.path));
return topMenu?.sidebarMenus || [];
};
const getAllMenus = (): MenuItem[] => {
const menus: MenuItem[] = [];
topMenus.value.forEach((topMenu) => {
if (topMenu.sidebarMenus) {
menus.push(...topMenu.sidebarMenus);
}
});
return menus;
};
const reset = () => {
topMenus.value = defaultTopMenus;
isMenusLoaded.value = true;
};
return {
topMenus,
isMenusLoaded,
setTopMenus,
getSidebarMenusByPath,
getAllMenus,
reset,
};
});
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body,
#app {
width: 100%;
height: 100%;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
font-size: 14px;
line-height: 1.5;
color: #333;
background-color: #f0f2f5;
}
a {
color: inherit;
text-decoration: none;
}
ul,
ol {
list-style: none;
}
.el-notification {
z-index: 9999 !important;
}
.el-notification__group {
margin: 0;
}
body {
position: relative;
}
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
$colors: (
'primary': (
'base': #3d6eff,
)
)
);
@use 'element-plus/theme-chalk/src/index.scss' as *;
@use './variables' as *;
@forward './variables';
@use './mixins' as *;
@forward './mixins';
@use './variables' as *;
@mixin input-focus-effect {
border-color: $primary-color !important;
box-shadow: 0 0 0 3px rgb(102 126 234 / 10%) !important;
}
@mixin input-error-effect {
border-color: $error-color !important;
box-shadow: 0 0 0 3px rgb(255 77 79 / 10%) !important;
}
@mixin input-base {
height: $input-height;
padding: 0 $input-padding;
background: $bg-white !important;
border: 1px solid $border-color !important;
border-radius: $border-radius !important;
box-shadow: none !important;
transition: $transition;
}
@mixin suffix-icon($size: 14px) {
display: inline-flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: $size;
min-width: $size;
height: $size;
min-height: $size;
margin-left: 0;
font-size: $size;
line-height: 1;
color: $text-placeholder;
cursor: pointer;
transition: color 0.3s;
&:hover {
color: $text-primary;
}
svg,
i {
display: block;
width: $size !important;
height: $size !important;
font-size: $size !important;
line-height: 1;
vertical-align: middle;
}
}
@mixin link-hover {
transition: color 0.3s;
&:hover {
color: $primary-hover;
}
}
@mixin button-hover {
box-shadow: 0 8px 20px rgb(102 126 234 / 30%) !important;
transform: translateY(-2px);
}
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
$primary-blue: #1956fe;
$primary-color: #667eea;
$primary-hover: #764ba2;
$border-color: #e0e0e0;
$border-radius: 8px;
$input-height: 48px;
$input-padding: 16px;
$transition: all 0.3s;
$font-size-base: 14px;
$font-size-lg: 16px;
$font-size-title: 28px;
$text-primary: #333;
$text-secondary: #666;
$text-placeholder: #999;
$bg-white: #fff;
$bg-disabled: #f5f5f5;
$bg-captcha: #f9f9f9;
$error-color: #ff4d4f;
$error-bg: #fff2f0;
$error-border: #ffccc7;
$btn-gradient: linear-gradient(135deg, #7fd6ff 0%, #026fff 100%);
export interface MenuItem {
id: string;
title: string;
path: string;
icon?: string;
children?: MenuItem[];
hidden?: boolean;
level?: number;
parentId?: string;
meta?: {
badge?: number | string;
externalLink?: string;
keepAlive?: boolean;
order?: number;
permission?: string;
requireAuth?: boolean;
showInBreadcrumb?: boolean;
};
}
export interface TopMenuItem {
id: string;
title: string;
path: string;
icon?: string;
sidebarMenus?: MenuItem[];
}
export interface BreadcrumbItem {
title: string;
path?: string;
}
<script setup lang="ts">
</script>
<template>
<div class="dashboard-page">
<h1>工作台</h1>
<p>欢迎使用后台管理系统</p>
</div>
</template>
<style scoped>
.dashboard-page {
padding: 24px;
}
.dashboard-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
.dashboard-page p {
font-size: 14px;
color: #666;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="home-page">
<router-view />
</div>
</template>
<style scoped>
.home-page {
width: 100%;
height: 100%;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="not-found-page">
<h1>404</h1>
<p>页面未找到</p>
</div>
</template>
<style scoped>
.not-found-page {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
padding: 24px;
}
.not-found-page h1 {
margin-bottom: 16px;
font-size: 48px;
font-weight: 600;
color: #333;
}
.not-found-page p {
font-size: 16px;
color: #666;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="order-detail-page">
<h1>订单详情</h1>
<p>订单详情页面</p>
</div>
</template>
<style scoped>
.order-detail-page {
padding: 24px;
}
.order-detail-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="order-list-page">
<h1>订单列表</h1>
<el-table :data="[]" style="width: 100%">
<el-table-column prop="orderNo" label="订单号" width="180" />
<el-table-column prop="amount" label="金额" width="180" />
<el-table-column prop="status" label="状态" />
</el-table>
</div>
</template>
<style scoped>
.order-list-page {
padding: 24px;
}
.order-list-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
import { ref } from 'vue'
const form = ref({
name: '',
price: 0
})
const handleSubmit = () => {
console.log('提交表单:', form.value)
// TODO: 实现提交逻辑
}
</script>
<template>
<div class="product-add-page">
<h1>添加产品</h1>
<el-form :model="form" label-width="100px">
<el-form-item label="产品名称">
<el-input v-model="form.name" placeholder="请输入产品名称" />
</el-form-item>
<el-form-item label="价格">
<el-input-number v-model="form.price" :min="0" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSubmit">提交</el-button>
</el-form-item>
</el-form>
</div>
</template>
<style scoped>
.product-add-page {
padding: 24px;
}
.product-add-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="product-list-page">
<h1>产品列表</h1>
<el-table :data="[]" style="width: 100%">
<el-table-column prop="name" label="产品名称" width="180" />
<el-table-column prop="price" label="价格" width="180" />
<el-table-column prop="stock" label="库存" />
</el-table>
</div>
</template>
<style scoped>
.product-list-page {
padding: 24px;
}
.product-list-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="menu-page">
<h1>菜单管理</h1>
<el-tree :data="[]" :props="{ children: 'children', label: 'label' }" />
</div>
</template>
<style scoped>
.menu-page {
padding: 24px;
}
.menu-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
</script>
<template>
<div class="role-page">
<h1>角色管理</h1>
<el-table :data="[]" style="width: 100%">
<el-table-column prop="name" label="角色名称" width="180" />
<el-table-column prop="description" label="描述" />
</el-table>
</div>
</template>
<style scoped>
.role-page {
padding: 24px;
}
.role-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
<script setup lang="ts">
import { GLButton, GLInput } from "@venus/common-ui-vue";
</script>
<template>
<div class="user-page">
<div class="search-section">
<GLInput placeholder="请输入用户名"
style="width: 200px; margin-right: 12px;" />
<GLButton type="primary">
查询
</GLButton>
</div>
<div class="action-section">
<GLButton type="primary">
编辑
</GLButton>
<GLButton type="danger">
删除
</GLButton>
<GLButton type="warning">
查询
</GLButton>
<GLButton type="success">
导出
</GLButton>
<GLButton type="info">
导入
</GLButton>
<GLButton type="primary">
刷新
</GLButton>
<GLButton type="danger">
打印
</GLButton>
<GLButton type="warning">
预览
</GLButton>
</div>
</div>
</template>
<style scoped>
.user-page {
padding: 24px;
}
.search-section {
margin-bottom: 24px;
display: flex;
align-items: center;
}
.action-section {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.user-page h1 {
margin-bottom: 16px;
font-size: 24px;
font-weight: 600;
color: #333;
}
</style>
{
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
"baseUrl": ".",
"module": "ESNext",
"moduleResolution": "bundler",
"paths": {
"@/*": ["src/*"],
"@venus/common-ui-vue": [
"../../packages/common-ui/vue-ui/src/index.ts"
]
},
"resolveJsonModule": true,
"typeRoots": ["../node_modules/@types", "./node_modules/@types"],
"allowImportingTsExtensions": true,
"allowJs": true,
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.js"
]
}
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
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 { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { defineConfig } from "vite";
// 获取 __dirname 的 ES 模块兼容方式
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default defineConfig(() => {
return {
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" ],
},
optimizeDeps: {
exclude: [ "@venus/common-ui-vue" ],
},
server: {
port: 8081,
cors: true,
host: true,
},
build: {
target: "esnext",
minify: false,
cssCodeSplit: false,
rollupOptions: {
external: [
"node:module",
"node:url",
"node:path",
"node:fs",
"node:process",
],
},
commonjsOptions: {
ignoreDynamicRequires: true,
},
},
};
});
# 构建产物
dist
*.log
# 依赖
node_modules
# IDE
.vscode
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# 临时文件
*.tmp
*.bak
.DS_Store
# 源代码
src/
# 示例
examples/
# 配置文件
*.config.ts
*.config.js
tsconfig.json
# 文档
*.md
!README.md
# 开发文件
.gitignore
.npmignore
# 测试
__tests__/
*.test.ts
*.spec.ts
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2024-11-13
### Added
- 🎉 初始版本发布
- ✨ 新增 `VButton` 按钮组件
- 支持加载状态
- 支持确认提示
- 支持防抖功能
- 支持权限控制
- 继承 Element Plus Button 所有功能
- ✨ 新增 `VSearchBox` 搜索框组件
- 支持防抖搜索
- 支持清空事件
- 支持回车搜索
- 支持自定义搜索按钮
- 多种尺寸支持
- 📝 完整的 TypeScript 类型定义
- 📚 详细的使用文档和示例
- 🎨 优雅的样式设计
### Features
#### VButton 特性
- 基于 Element Plus ElButton 二次封装
- 提供更便捷的业务功能
- 完整的 TypeScript 支持
- 支持所有 Element Plus Button 属性
#### VSearchBox 特性
- 基于 Element Plus ElInput 二次封装
- 自动防抖搜索
- 支持多种事件监听
- 美观的搜索按钮样式
- 响应式设计
[1.0.0]: https://github.com/venusjs/vue-venus-admin/releases/tag/common-ui-v1.0.0
# @venus/common-ui 集成说明
## 在微前端基座中的使用示例
### 1. 引入组件
在 `Home.vue` 中引入公共组件库:
```typescript
import { VButton, VSearchBox } from "@venus/common-ui";
import { ElMessage } from "element-plus";
```
### 2. 组件使用示例
#### VSearchBox - 搜索框组件
```vue
<template>
<VSearchBox
v-model="searchKeyword"
placeholder="请输入搜索关键词"
:debounce="300"
@search="handleSearch"
@clear="handleClearSearch" />
</template>
<script setup lang="ts">
import { ref } from "vue";
import { VSearchBox } from "@venus/common-ui";
const searchKeyword = ref("");
const handleSearch = (value: string) => {
console.log("搜索关键词:", value);
// 执行搜索逻辑
};
const handleClearSearch = () => {
console.log("搜索框已清空");
};
</script>
```
**特性:**
- ✓ 支持 v-model 双向绑定
- ✓ 内置防抖功能(可配置延迟时间)
- ✓ 支持清空按钮和清空事件
- ✓ 支持回车键搜索
- ✓ 可选搜索按钮
- ✓ 支持多种尺寸(large / default / small)
#### VButton - 按钮组件
```vue
<template>
<!-- 基础使用 -->
<VButton type="primary" @click="handleClick">点击按钮</VButton>
<!-- 加载状态 -->
<VButton type="primary" :loading="isLoading" @click="handleAsync">异步操作</VButton>
<!-- 确认提示 -->
<VButton type="danger" confirm-text="确定要删除吗?" @click="handleDelete">删除</VButton>
<!-- 防抖 -->
<VButton type="primary" :debounce="500" @click="handleClick">防抖按钮</VButton>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { VButton } from "@venus/common-ui";
const isLoading = ref(false);
const handleClick = () => {
console.log("按钮被点击");
};
const handleAsync = async () => {
isLoading.value = true;
// 执行异步操作
await someAsyncOperation();
isLoading.value = false;
};
const handleDelete = () => {
console.log("删除操作已确认");
};
</script>
```
**特性:**
- ✓ 继承 Element Plus Button 所有属性和功能
- ✓ 内置加载状态管理
- ✓ 支持点击前确认提示
- ✓ 内置防抖功能(可配置延迟时间)
- ✓ 支持权限控制(预留接口)
- ✓ 完整的 TypeScript 类型支持
### 3. 在其他微应用中使用
#### 方式一:全局注册(推荐)
在微应用的入口文件(如 `main.ts`)中:
```typescript
import { createApp } from "vue";
import CommonUI from "@venus/common-ui";
import App from "./App.vue";
const app = createApp(App);
app.use(CommonUI);
app.mount("#app");
```
#### 方式二:按需引入
```typescript
import { VButton, VSearchBox } from '@venus/common-ui';
// 在组件中直接使用
<template>
<VButton type="primary">按钮</VButton>
<VSearchBox v-model="keyword" @search="handleSearch" />
</template>
```
### 4. TypeScript 支持
```typescript
import type { VButtonProps, VSearchBoxProps } from "@venus/common-ui";
// 享受完整的类型提示和检查
const buttonProps: VButtonProps = {
type: "primary",
loading: false,
debounce: 300,
};
const searchProps: VSearchBoxProps = {
modelValue: "",
placeholder: "请输入",
debounce: 300,
};
```
### 5. 在主应用中查看示例
启动主应用后,访问首页即可看到完整的组件展示和使用示例:
```bash
# 安装依赖
pnpm install
# 启动主应用
pnpm dev
```
访问 `http://localhost:5173`,向下滚动到 "**@venus/common-ui 公共组件库示例**" 部分。
### 6. 组件 API 参考
详细的 API 文档请参考:
- [VButton API](./src/components/button/index.vue)
- [VSearchBox API](./src/components/search-box/index.vue)
- [类型定义](./src/types.ts)
### 7. 扩展开发
如需添加新组件,请按以下步骤操作:
1. 在 `src/components/` 下创建新组件目录
2. 实现组件逻辑和样式
3. 在 `src/components/index.ts` 中导出组件
4. 在 `src/index.ts` 中注册组件
5. 更新类型定义(`src/types.ts`)
6. 运行 `pnpm build` 构建组件库
## 注意事项
- 所有组件基于 Element Plus 二次封装,确保项目已安装 Element Plus
- 组件库使用 TypeScript 开发,建议在 TypeScript 项目中使用以获得最佳体验
- 确保 Vue 版本 >= 3.3.0,Element Plus 版本 >= 2.0.0
## 常见问题
### Q: 组件样式不生效?
A: 确保已正确引入 Element Plus 的样式文件。
### Q: TypeScript 类型报错?
A: 检查 `tsconfig.json` 配置,确保正确配置了类型解析路径。
### Q: 组件热更新不生效?
A: 在开发模式下,组件库使用源码引入(development 模式),修改后会自动热更新。
---
更多问题请查看 [README.md](./README.md) 或提交 Issue。
# @venus/common-ui
Venus Pro 通用 UI 组件库 - 基于 Element Plus 的二次封装
## 简介
这是一个基于 Element Plus 的二次封装组件库,提供更符合业务需求的组件 API 和默认配置。
## 安装
```bash
pnpm add @venus/common-ui
```
## 使用
```typescript
import { VButton, VSearchBox } from "@venus/common-ui";
```
## 组件列表
### VButton - 按钮组件
增强型按钮组件,提供加载状态、权限控制等功能。
```vue
<VButton type="primary" :loading="isLoading" @click="handleClick">
提交
</VButton>
```
### VSearchBox - 搜索框组件
增强型搜索框,支持防抖、清空、搜索事件等功能。
```vue
<VSearchBox v-model="searchText" placeholder="请输入搜索内容" @search="handleSearch" />
```
## 特性
- 🎨 基于 Element Plus,保持统一的设计风格
- 📦 开箱即用的业务组件
- 🔧 灵活的配置和扩展
- 💪 TypeScript 支持
- 🎯 专注于业务场景
## License
MIT
# @venus/common-ui 使用指南
## 安装
在项目的 `package.json` 中添加依赖:
```json
{
"dependencies": {
"@venus/common-ui": "workspace:*"
}
}
```
然后运行:
```bash
pnpm install
```
## 全局注册
在你的 Vue 应用入口文件中:
```typescript
import { createApp } from "vue";
import App from "./App.vue";
import VenusUI from "@venus/common-ui";
const app = createApp(App);
// 全局注册所有组件
app.use(VenusUI);
app.mount("#app");
```
## 按需引入
```vue
<script setup lang="ts">
import { VButton, VSearchBox } from "@venus/common-ui";
</script>
```
## 组件使用示例
### VButton 按钮组件
#### 基础用法
```vue
<template>
<VButton>默认按钮</VButton>
<VButton type="primary">主要按钮</VButton>
<VButton type="success">成功按钮</VButton>
<VButton type="warning">警告按钮</VButton>
<VButton type="danger">危险按钮</VButton>
<VButton type="info">信息按钮</VButton>
</template>
```
#### 加载状态
```vue
<script setup lang="ts">
import { ref } from "vue";
import { VButton } from "@venus/common-ui";
const loading = ref(false);
const handleSubmit = async () => {
loading.value = true;
try {
// 执行异步操作
await someAsyncOperation();
} finally {
loading.value = false;
}
};
</script>
<template>
<VButton type="primary" :loading="loading" @click="handleSubmit">提交</VButton>
</template>
```
#### 确认提示
```vue
<template>
<VButton type="danger" confirm-text="确定要删除吗?" @click="handleDelete">删除</VButton>
</template>
```
#### 防抖功能
```vue
<template>
<!-- 300ms 防抖 -->
<VButton type="primary" :debounce="300" @click="handleSave">保存</VButton>
</template>
```
#### 权限控制
```vue
<template>
<!-- 只有拥有 'user:delete' 权限的用户才能看到此按钮 -->
<VButton type="danger" permission="user:delete" @click="handleDelete">删除用户</VButton>
</template>
```
### VSearchBox 搜索框组件
#### 基础用法
```vue
<script setup lang="ts">
import { ref } from "vue";
import { VSearchBox } from "@venus/common-ui";
const searchText = ref("");
const handleSearch = (value: string) => {
console.log("搜索:", value);
// 执行搜索逻辑
};
</script>
<template>
<VSearchBox v-model="searchText" placeholder="请输入搜索内容" @search="handleSearch" />
</template>
```
#### 不显示搜索按钮
```vue
<template>
<VSearchBox v-model="searchText" :show-search-button="false" @search="handleSearch" />
</template>
```
#### 自定义防抖时间
```vue
<template>
<!-- 500ms 防抖 -->
<VSearchBox v-model="searchText" :debounce="500" @search="handleSearch" />
</template>
```
#### 监听清空事件
```vue
<script setup lang="ts">
const handleClear = () => {
console.log("搜索框已清空");
// 执行清空后的逻辑,比如重置列表
};
</script>
<template>
<VSearchBox v-model="searchText" @search="handleSearch" @clear="handleClear" />
</template>
```
#### 不同尺寸
```vue
<template>
<VSearchBox v-model="searchText" size="large" />
<VSearchBox v-model="searchText" size="default" />
<VSearchBox v-model="searchText" size="small" />
</template>
```
#### 禁用状态
```vue
<template>
<VSearchBox v-model="searchText" disabled />
</template>
```
## 完整示例
```vue
<script setup lang="ts">
import { ref, reactive } from "vue";
import { VButton, VSearchBox } from "@venus/common-ui";
import { ElMessage } from "element-plus";
// 搜索相关
const searchText = ref("");
const handleSearch = (value: string) => {
console.log("搜索:", value);
ElMessage.success(`正在搜索: ${value}`);
};
const handleClear = () => {
ElMessage.info("搜索已清空");
};
// 表单相关
const loading = ref(false);
const formData = reactive({
name: "",
email: "",
});
const handleSubmit = async () => {
loading.value = true;
try {
// 模拟API调用
await new Promise((resolve) => setTimeout(resolve, 2000));
ElMessage.success("提交成功");
} catch (error) {
ElMessage.error("提交失败");
} finally {
loading.value = false;
}
};
const handleDelete = () => {
ElMessage.success("删除成功");
};
const handleSave = () => {
ElMessage.success("保存成功");
};
</script>
<template>
<div class="demo-container">
<h2>搜索功能</h2>
<VSearchBox
v-model="searchText"
placeholder="搜索用户..."
:debounce="300"
@search="handleSearch"
@clear="handleClear" />
<h2>按钮示例</h2>
<div class="button-group">
<VButton type="primary" :loading="loading" @click="handleSubmit">提交表单</VButton>
<VButton type="danger" confirm-text="确定要删除吗?此操作不可恢复!" @click="handleDelete">
删除数据
</VButton>
<VButton type="success" :debounce="500" @click="handleSave">保存草稿</VButton>
</div>
</div>
</template>
<style scoped>
.demo-container {
padding: 20px;
}
.button-group {
display: flex;
gap: 10px;
margin-top: 20px;
}
h2 {
margin: 20px 0 10px;
}
</style>
```
## TypeScript 类型支持
所有组件都提供完整的 TypeScript 类型定义:
```typescript
import type { VButtonProps, VSearchBoxProps } from "@venus/common-ui";
// 使用类型
const buttonProps: VButtonProps = {
type: "primary",
loading: true,
debounce: 300,
};
const searchProps: VSearchBoxProps = {
modelValue: "",
placeholder: "搜索",
debounce: 500,
};
```
## API 文档
### VButton Props
| 属性 | 说明 | 类型 | 默认值 |
| ----------- | ---------------- | ------------------------------------------------------------------------ | ----------- |
| type | 按钮类型 | `'default' \| 'primary' \| 'success' \| 'warning' \| 'danger' \| 'info'` | `'default'` |
| loading | 是否加载中 | `boolean` | `false` |
| disabled | 是否禁用 | `boolean` | `false` |
| permission | 权限码 | `string` | - |
| confirmText | 确认提示文本 | `string` | - |
| debounce | 防抖时间(毫秒) | `number` | `0` |
继承 Element Plus ElButton 的所有属性。
### VButton Events
| 事件名 | 说明 | 参数 |
| ------ | -------- | ----------------------------- |
| click | 点击事件 | `(event: MouseEvent) => void` |
### VSearchBox Props
| 属性 | 说明 | 类型 | 默认值 |
| ---------------- | ---------------- | --------------------------------- | ------------------ |
| modelValue | 绑定值 | `string` | `''` |
| placeholder | 占位符 | `string` | `'请输入搜索内容'` |
| clearable | 是否可清空 | `boolean` | `true` |
| debounce | 防抖延迟(毫秒) | `number` | `300` |
| showSearchButton | 是否显示搜索按钮 | `boolean` | `true` |
| searchButtonText | 搜索按钮文本 | `string` | `'搜索'` |
| size | 输入框尺寸 | `'large' \| 'default' \| 'small'` | `'default'` |
| maxlength | 最大长度 | `number` | - |
| disabled | 是否禁用 | `boolean` | `false` |
| prefixIcon | 搜索图标 | `string \| Component` | `Search` |
### VSearchBox Events
| 事件名 | 说明 | 参数 |
| ----------------- | ---------- | ------------------------- |
| update:modelValue | 输入值变化 | `(value: string) => void` |
| search | 搜索事件 | `(value: string) => void` |
| clear | 清空事件 | `() => void` |
| input | 输入事件 | `(value: string) => void` |
## 注意事项
1. **Element Plus 依赖**:本组件库依赖 Element Plus,请确保项目中已安装并正确配置 Element Plus。
2. **样式引入**:如果使用按需引入,请确保引入了 Element Plus 的样式:
```typescript
import "element-plus/dist/index.css";
```
3. **图标**:搜索框组件使用了 Element Plus 的图标,确保图标已正确配置。
4. **防抖**:搜索框的防抖功能会在输入时自动触发搜索,如果不需要此功能,可以将 `debounce` 设置为 `0`。
5. **权限控制**:按钮的权限控制功能需要配合项目的权限系统使用,你需要在组件内部实现 `hasPermission` 函数。
import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
clean: true,
declaration: true,
entries: [ "src/index" ],
externals: [ "vue", "element-plus", "@vueuse/core" ],
});
<template>
<div class="example-container">
<h1>@venus/common-ui 组件示例</h1>
<!-- 搜索框示例 -->
<section class="section">
<h2>VSearchBox - 搜索框组件</h2>
<div class="demo-block">
<h3>基础用法</h3>
<VSearchBox v-model="searchText"
placeholder="请输入搜索内容..."
@clear="handleClear"
@search="handleSearch" />
<p class="hint">
当前搜索值: {{ searchText }}
</p>
</div>
<div class="demo-block">
<h3>不显示搜索按钮</h3>
<VSearchBox v-model="searchText"
placeholder="输入后回车搜索"
:show-search-button="false"
@search="handleSearch" />
</div>
<div class="demo-block">
<h3>不同尺寸</h3>
<div class="size-group">
<VSearchBox v-model="searchText"
placeholder="大尺寸"
size="large"
@search="handleSearch" />
<VSearchBox v-model="searchText"
placeholder="默认尺寸"
size="default"
@search="handleSearch" />
<VSearchBox v-model="searchText"
placeholder="小尺寸"
size="small"
@search="handleSearch" />
</div>
</div>
<div class="demo-block">
<h3>禁用状态</h3>
<VSearchBox v-model="searchText"
disabled
placeholder="禁用状态" />
</div>
<div class="demo-block">
<h3>自定义防抖时间</h3>
<VSearchBox v-model="searchText"
:debounce="1000"
placeholder="1秒防抖"
@search="handleSearch" />
<p class="hint">
输入后 1 秒才会触发搜索
</p>
</div>
</section>
<!-- 按钮示例 -->
<section class="section">
<h2>VButton - 按钮组件</h2>
<div class="demo-block">
<h3>按钮类型</h3>
<div class="button-group">
<VButton>默认按钮</VButton>
<VButton type="primary">
主要按钮
</VButton>
<VButton type="success">
成功按钮
</VButton>
<VButton type="warning">
警告按钮
</VButton>
<VButton type="danger">
危险按钮
</VButton>
<VButton type="info">
信息按钮
</VButton>
</div>
</div>
<div class="demo-block">
<h3>加载状态</h3>
<div class="button-group">
<VButton :loading="loading"
type="primary"
@click="handleSubmit">
{{ loading ? "提交中..." : "提交表单" }}
</VButton>
<VButton loading type="primary">
加载中
</VButton>
</div>
</div>
<div class="demo-block">
<h3>禁用状态</h3>
<div class="button-group">
<VButton disabled>
默认按钮
</VButton>
<VButton disabled type="primary">
主要按钮
</VButton>
<VButton disabled type="success">
成功按钮
</VButton>
</div>
</div>
<div class="demo-block">
<h3>确认提示</h3>
<div class="button-group">
<VButton confirm-text="确定要删除这条数据吗?此操作不可恢复!"
type="danger"
@click="handleDelete">
删除数据
</VButton>
<VButton confirm-text="确定要重置所有设置吗?"
type="warning"
@click="handleSave">
重置设置
</VButton>
</div>
<p class="hint">
点击按钮会弹出确认对话框
</p>
</div>
<div class="demo-block">
<h3>防抖功能</h3>
<div class="button-group">
<VButton :debounce="500"
type="primary"
@click="handleQuickClick">
500ms 防抖
</VButton>
<VButton :debounce="1000"
type="success"
@click="handleQuickClick">
1000ms 防抖
</VButton>
</div>
<p class="hint">
快速连续点击,只会触发一次
</p>
</div>
<div class="demo-block">
<h3>按钮尺寸</h3>
<div class="button-group">
<VButton size="large" type="primary">
大型按钮
</VButton>
<VButton size="default" type="primary">
默认按钮
</VButton>
<VButton size="small" type="primary">
小型按钮
</VButton>
</div>
</div>
<div class="demo-block">
<h3>图标按钮</h3>
<div class="button-group">
<VButton icon="Search" type="primary">
搜索
</VButton>
<VButton icon="Check" type="success">
确认
</VButton>
<VButton icon="Edit" type="warning">
编辑
</VButton>
<VButton icon="Delete" type="danger">
删除
</VButton>
</div>
</div>
</section>
<!-- 组合示例 -->
<section class="section">
<h2>组合示例</h2>
<div class="demo-block">
<h3>搜索和操作</h3>
<div class="combined-demo">
<VSearchBox v-model="searchText"
placeholder="搜索用户..."
style="flex: 1"
@search="handleSearch" />
<div class="button-group" style="margin-left: 12px">
<VButton icon="Plus" type="primary">
新增
</VButton>
<VButton icon="Upload" type="success">
导入
</VButton>
<VButton icon="Download" type="warning">
导出
</VButton>
</div>
</div>
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { VButton, VSearchBox } from "../src";
// 搜索示例
const searchText = ref("");
const handleSearch = (value: string) => {
console.log("搜索内容:", value);
ElMessage.success(`正在搜索: ${value || "空"}`);
};
const handleClear = () => {
ElMessage.info("搜索框已清空");
};
// 按钮示例
const loading = ref(false);
const handleSubmit = async () => {
loading.value = true;
ElMessage.info("提交中...");
// 模拟 API 调用
await new Promise((resolve) => setTimeout(resolve, 2000));
loading.value = false;
ElMessage.success("提交成功!");
};
const handleDelete = () => {
ElMessage.success("删除成功!");
};
const handleSave = () => {
ElMessage.success("保存成功!");
};
const handleQuickClick = () => {
ElMessage.info("点击事件触发");
};
</script>
<style scoped>
/* 响应式 */
@media (max-width: 768px) {
.example-container {
padding: 16px;
}
.button-group {
gap: 8px;
}
.combined-demo {
flex-direction: column;
align-items: stretch;
}
.combined-demo .button-group {
margin-top: 12px;
margin-left: 0 !important;
}
}
.example-container {
max-width: 1200px;
padding: 24px;
margin: 0 auto;
}
h1 {
margin-bottom: 32px;
font-size: 32px;
font-weight: bold;
color: #303133;
}
.section {
margin-bottom: 48px;
}
.section h2 {
padding-bottom: 8px;
margin-bottom: 24px;
font-size: 24px;
font-weight: 600;
color: #409eff;
border-bottom: 2px solid #409eff;
}
.demo-block {
padding: 24px;
margin-bottom: 32px;
background: #f5f7fa;
border-radius: 8px;
}
.demo-block h3 {
margin-bottom: 16px;
font-size: 16px;
font-weight: 600;
color: #606266;
}
.button-group {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}
.size-group {
display: flex;
flex-direction: column;
gap: 12px;
}
.hint {
margin-top: 12px;
font-size: 14px;
color: #909399;
}
.combined-demo {
display: flex;
gap: 12px;
align-items: center;
}
</style>
export { default, default as VButton } from "./index.vue";
<template>
<!-- 用计算属性过滤并批量绑定 -->
<ElButton v-bind="elButtonProps" @click="debouncedClick">
<slot />
</ElButton>
</template>
<script setup lang="ts">
import type { VButtonProps } from "../../types";
import { computed, ref } from "vue";
import { useDebounceFn } from "@vueuse/core";
import { ElButton, ElMessageBox } from "element-plus";
/**
* VButton - 增强型按钮组件
* 基于 Element Plus ElButton 的二次封装
* 提供加载状态、权限控制、确认提示、防抖等功能
*/
defineOptions({
name: "VButton",
});
const props = withDefaults(defineProps<VButtonProps>(), {
loading: false,
disabled: false,
permission: undefined,
confirmText: undefined,
debounce: 0,
});
const emit = defineEmits<{
click: [event: MouseEvent];
}>();
// 内部加载状态
const internalLoading = ref(false);
// 计算最终的加载状态
const isLoading = computed(() => props.loading || internalLoading.value);
// 计算是否禁用
const isDisabled = computed(() => {
if (props.disabled) return true;
// 这里可以添加权限判断逻辑
// if (props.permission && !hasPermission(props.permission)) return true;
return false;
});
// 提取所有需要传递给 ElButton 的原生属性
const elButtonProps = computed(() => {
const { permission, confirmText, debounce, loading, disabled, ...restProps } = props;
return {
...restProps,
loading: isLoading.value,
disabled: isDisabled.value,
};
});
// 处理点击事件
const handleClick = async (event: MouseEvent) => {
if (isLoading.value || isDisabled.value) return;
// 如果设置了确认文本,则显示确认框
if (props.confirmText) {
try {
await ElMessageBox.confirm(props.confirmText, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
} catch {
// 用户取消
return;
}
}
emit("click", event);
};
// 防抖处理
const debouncedClick = props.debounce ? useDebounceFn(handleClick, props.debounce) : handleClick;
</script>
export { VButton } from "./button";
export { VSearchBox } from "./search-box";
export { default, default as VSearchBox } from "./index.vue";
\ No newline at end of file \ No newline at end of file
<template>
<div class="v-search-box">
<ElInput v-model="inputValue"
class="v-search-box__input"
:clearable="clearable"
:disabled="disabled"
:maxlength="maxlength"
:placeholder="placeholder"
:prefix-icon="prefixIcon || Search"
:size="size"
@clear="handleClear"
@keyup.enter="handleKeyEnter">
<template v-if="showSearchButton" #append>
<el-button :disabled="disabled"
:icon="Search"
:size="size"
@click="() => handleSearch()">
{{ searchButtonText }}
</el-button>
</template>
<!-- 透传所有插槽 -->
<template v-for="(_, name) in $slots" #[name]="slotProps">
<slot :name="name" v-bind="slotProps || {}" />
</template>
</ElInput>
</div>
</template>
<script setup lang="ts">
import type { VSearchBoxEmits, VSearchBoxProps } from "../../types";
import { computed } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useDebounceFn } from "@vueuse/core";
import { ElInput } from "element-plus";
/**
* VSearchBox - 搜索框组件
* 基于 Element Plus ElInput 的二次封装
* 提供防抖搜索、清空、回车搜索等功能
*/
defineOptions({
name: "VSearchBox",
});
const props = withDefaults(defineProps<VSearchBoxProps>(), {
modelValue: "",
placeholder: "请输入搜索内容",
clearable: true,
debounce: 300,
showSearchButton: true,
searchButtonText: "搜索",
size: "default",
disabled: false,
prefixIcon: undefined,
});
const emit = defineEmits<VSearchBoxEmits>();
// 计算输入框的值
const inputValue = computed({
get: () => props.modelValue,
set: (value: string) => {
emit("update:modelValue", value);
emit("input", value);
// 触发防抖搜索
if (props.debounce > 0) {
debouncedSearch(value);
}
},
});
// 处理搜索
const handleSearch = (value?: string) => {
const searchValue = value ?? inputValue.value;
emit("search", searchValue);
};
// 防抖搜索
const debouncedSearch = useDebounceFn((value: string) => {
emit("search", value);
}, props.debounce);
// 处理清空
const handleClear = () => {
emit("clear");
emit("search", "");
};
// 处理回车
const handleKeyEnter = () => {
handleSearch();
};
</script>
<style scoped>
.v-search-box {
display: inline-block;
width: 100%;
}
.v-search-box__input {
width: 100%;
}
/* 搜索按钮样式优化 */
:deep(.el-input-group__append) {
padding: 0;
color: #fff;
background-color: var(--el-color-primary);
border-color: var(--el-color-primary);
}
:deep(.el-input-group__append .el-button) {
margin: 0;
color: inherit;
background-color: transparent;
border: none;
}
:deep(.el-input-group__append .el-button:hover) {
background-color: rgb(255 255 255 / 10%);
}
</style>
/**
* @venus/common-ui
* Venus Pro 通用 UI 组件库
* 基于 Element Plus 的二次封装
*/
import type { App } from "vue";
// 导出所有组件
// 导入组件
import { VButton } from "./components/button";
import { VSearchBox } from "./components/search-box";
export * from "./components";
// 导出类型
export * from "./types";
// 组件列表
const components = [ VButton, VSearchBox ];
/**
* 安装所有组件
* @param app Vue 应用实例
*/
const install = (app: App) => {
components.forEach((component) => {
app.component(component.name || "", component);
});
};
export default {
install,
VButton,
VSearchBox,
};
import type { ButtonProps } from "element-plus";
/**
* 按钮组件属性
* 继承 Element Plus ButtonProps,并扩展自定义功能
*/
export interface VButtonProps extends /* @vue-ignore */ ButtonProps {
/**
* 确认提示文本,设置后点击会弹出确认框
*/
confirmText?: string;
/**
* 防抖时间(毫秒)
*/
debounce?: number;
/**
* 权限码,用于权限控制
*/
permission?: string;
}
/**
* 搜索框组件属性
*/
export interface VSearchBoxProps {
/**
* 是否可清空
*/
clearable?: boolean;
/**
* 防抖延迟(毫秒)
*/
debounce?: number;
/**
* 是否禁用
*/
disabled?: boolean;
/**
* 最大长度
*/
maxlength?: number;
/**
* 绑定值
*/
modelValue?: string;
/**
* 占位符
*/
placeholder?: string;
/**
* 搜索图标
*/
prefixIcon?: string;
/**
* 搜索按钮文本
*/
searchButtonText?: string;
/**
* 是否显示搜索按钮
*/
showSearchButton?: boolean;
/**
* 输入框尺寸
*/
size?: "default" | "large" | "small";
}
/**
* 搜索框组件事件
*/
export interface VSearchBoxEmits {
/**
* 输入值变化事件
*/
(e: "input"|"search" |"update:modelValue", value: string): void;
/**
* 清空事件
*/
(e: "clear"): void;
/**
* 输入事件
*/
}
...@@ -4,5 +4,16 @@ export default defineBuildConfig({ ...@@ -4,5 +4,16 @@ export default defineBuildConfig({
clean: true, clean: true,
declaration: true, declaration: true,
entries: [ "src/index" ], entries: [ "src/index" ],
externals: [ "vue", "element-plus", "@vueuse/core" ], externals: [
"vue",
"element-plus",
"@vueuse/core",
"@element-plus/icons-vue",
],
rollup: {
emitCJS: false,
esbuild: {
target: "es2015",
},
},
}); });
...@@ -16,9 +16,14 @@ ...@@ -16,9 +16,14 @@
"stub": "pnpm unbuild --stub" "stub": "pnpm unbuild --stub"
}, },
"files": [ "files": [
"dist" "dist",
"src"
],
"sideEffects": [
"**/*.css",
"**/*.scss",
"**/*.vue"
], ],
"sideEffects": false,
"main": "./dist/index.mjs", "main": "./dist/index.mjs",
"module": "./dist/index.mjs", "module": "./dist/index.mjs",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
......
<script setup lang="ts">
defineOptions({
name: "GLButton",
});
</script>
<template> <template>
<ElButton v-bind="$attrs"> <ElButton v-bind="$attrs">
<template v-for="(_, name) in $slots" <template v-for="(_, name) in $slots"
......
<script setup lang="ts">
defineOptions({
name: "GLInput",
});
</script>
<template> <template>
<ElInput v-bind="$attrs" class="gl-input"> <ElInput v-bind="$attrs" class="gl-input">
<template v-for="(_, name) in $slots" <template v-for="(_, name) in $slots"
......
...@@ -402,7 +402,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[] ...@@ -402,7 +402,7 @@ export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[]
id: routeId, id: routeId,
title: file.title, title: file.title,
icon: file.routeConfig.meta?.icon || "", icon: file.routeConfig.meta?.icon || "",
level: 0, // index 文件默认为 0 level: 1, // index 文件默认为 1
hidden: file.routeConfig.hidden ?? false, hidden: file.routeConfig.hidden ?? false,
meta: { meta: {
authority: file.routeConfig.meta?.authority || authority, authority: file.routeConfig.meta?.authority || authority,
......
...@@ -737,6 +737,55 @@ importers: ...@@ -737,6 +737,55 @@ importers:
specifier: ^1.5.0 specifier: ^1.5.0
version: 1.6.4(@algolia/client-search@5.46.2)(@types/node@24.10.4)(async-validator@4.2.5)(axios@1.13.2)(jiti@2.6.1)(postcss@8.5.6)(sass@1.97.2)(search-insights@2.17.3)(sortablejs@1.15.6)(terser@5.44.1)(typescript@5.9.3)(yaml@2.8.2) version: 1.6.4(@algolia/client-search@5.46.2)(@types/node@24.10.4)(async-validator@4.2.5)(axios@1.13.2)(jiti@2.6.1)(postcss@8.5.6)(sass@1.97.2)(search-insights@2.17.3)(sortablejs@1.15.6)(terser@5.44.1)(typescript@5.9.3)(yaml@2.8.2)
example:
dependencies:
'@element-plus/icons-vue':
specifier: 'catalog:'
version: 2.3.2(vue@3.5.26(typescript@5.9.3))
'@venus/common-ui-vue':
specifier: workspace:*
version: link:../packages/common-ui/vue-ui
'@vueuse/core':
specifier: 'catalog:'
version: 13.9.0(vue@3.5.26(typescript@5.9.3))
element-plus:
specifier: 'catalog:'
version: 2.13.0(vue@3.5.26(typescript@5.9.3))
pinia:
specifier: ^3.0.3
version: 3.0.4(typescript@5.9.3)(vue@3.5.26(typescript@5.9.3))
vue:
specifier: ^3.5.17
version: 3.5.26(typescript@5.9.3)
vue-router:
specifier: 'catalog:'
version: 4.6.4(vue@3.5.26(typescript@5.9.3))
devDependencies:
'@types/node':
specifier: ^24.9.2
version: 24.10.4
'@vitejs/plugin-vue':
specifier: 'catalog:'
version: 6.0.3(vite@7.3.1(@types/node@24.10.4)(jiti@2.6.1)(sass@1.97.2)(terser@5.44.1)(yaml@2.8.2))(vue@3.5.26(typescript@5.9.3))
'@vitejs/plugin-vue-jsx':
specifier: 'catalog:'
version: 5.1.3(vite@7.3.1(@types/node@24.10.4)(jiti@2.6.1)(sass@1.97.2)(terser@5.44.1)(yaml@2.8.2))(vue@3.5.26(typescript@5.9.3))
typescript:
specifier: 'catalog:'
version: 5.9.3
unplugin-auto-import:
specifier: 'catalog:'
version: 0.17.8(@vueuse/core@13.9.0(vue@3.5.26(typescript@5.9.3)))(rollup@4.55.1)
unplugin-vue-components:
specifier: 'catalog:'
version: 0.26.0(@babel/parser@7.28.5)(rollup@4.55.1)(vue@3.5.26(typescript@5.9.3))
vite:
specifier: ^7.1.2
version: 7.3.1(@types/node@24.10.4)(jiti@2.6.1)(sass@1.97.2)(terser@5.44.1)(yaml@2.8.2)
vue-tsc:
specifier: 'catalog:'
version: 2.2.10(typescript@5.9.3)
internal/lint-configs/commitlint-config: internal/lint-configs/commitlint-config:
dependencies: dependencies:
'@commitlint/cli': '@commitlint/cli':
......
...@@ -11,6 +11,7 @@ packages: ...@@ -11,6 +11,7 @@ packages:
- packages/cli/* - packages/cli/*
- packages/utils/* - packages/utils/*
- packages/common-ui/* - packages/common-ui/*
- packages/common-ui/vue-ui
- apps/* - apps/*
- apps/miniprogram/**/* - apps/miniprogram/**/*
...@@ -18,6 +19,7 @@ packages: ...@@ -18,6 +19,7 @@ packages:
- apps/uniapp/**/* - apps/uniapp/**/*
- scripts/**/* - scripts/**/*
- docs - docs
- example
catalog: catalog:
"eslint-plugin-wxml": ^0.8.0 "eslint-plugin-wxml": ^0.8.0
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!