优化更新

This commit is contained in:
2026-09-13 17:33:13 +08:00
parent 8be23a62a3
commit 7f758cc6e9
97 changed files with 2333 additions and 3595 deletions
@@ -164,13 +164,13 @@ transformRequestData: (res: AxiosResponse<Result>, options: RequestOptions) => {
// 业务失败(code === 1)
if (code === ResultEnum.ERROR) {
ElMessage.error(msg);
message.error(msg);
throw new Error(msg);
}
// 登录超时(code === 401)
if (code === ResultEnum.TIMEOUT) {
ElMessageBox.confirm('登录身份已失效,请重新登录!', '提示', { ... })
Modal.confirm({ title: '提示', content: '登录身份已失效,请重新登录!', ... })
.then(() => {
storage.clear();
window.location.href = '/login';
@@ -214,18 +214,18 @@ const handleSubmit = async () => {
错误处理分两层:
1. **业务错误**(code !== 0):拦截器统一弹出 `ElMessage.error(msg)`,并 `throw new Error`
1. **业务错误**(code !== 0):拦截器统一弹出 `message.error(msg)`,并 `throw new Error`
2. **HTTP 错误**(网络异常、超时等):`responseInterceptorsCatch` 处理
```typescript
responseInterceptorsCatch: (error: any) => {
const { response, code } = error || {};
if (code === 'ECONNABORTED') {
ElMessage.error('接口请求超时,请刷新页面重试!');
message.error('接口请求超时,请刷新页面重试!');
return;
}
if (error.toString().includes('Network Error')) {
ElMessageBox.confirm('请检查您的网络连接是否正常', '网络异常', { ... });
Modal.confirm({ title: '网络异常', content: '请检查您的网络连接是否正常', ... });
return Promise.reject(error);
}
checkStatus(error.response?.status, response?.data?.msg);
@@ -68,8 +68,8 @@ Vite 按 mode 加载环境变量,后面的文件覆盖前面的:
|------|------|--------|------|
| `VITE_PORT` | `number` | `8001` | 开发服务器端口 |
| `VITE_PUBLIC_PATH` | `string` | `/` | 部署基础路径(子目录部署时修改) |
| `VITE_GLOB_APP_TITLE` | `string` | `Django+ElementPlus版` | 应用标题(注入 HTML) |
| `VITE_GLOB_APP_SHORT_NAME` | `string` | `Django+ElementPlus版` | 应用短名(用于生成运行时配置变量名) |
| `VITE_GLOB_APP_TITLE` | `string` | `Django+AntDesign版` | 应用标题(注入 HTML) |
| `VITE_GLOB_APP_SHORT_NAME` | `string` | `Django+AntDesign版` | 应用短名(用于生成运行时配置变量名) |
| `VITE_GLOB_API_URL` | `string` | 空 | API 基础路径(留空使用相对路径) |
| `VITE_GLOB_API_URL_PREFIX` | `string` | `/api` | API 前缀 |
| `VITE_GLOB_FILE_URL` | `string` | - | 文件访问域名(拼接上传文件 URL) |
@@ -177,7 +177,7 @@ import { defineStore } from 'pinia'; // 自动
```html
<!-- 构建后的 index.html -->
<title>Django+ElementPlus版</title>
<title>Django+AntDesign版</title>
<script src="/app.config.js?v=1.0.0-1725000000000"></script>
```
@@ -192,7 +192,7 @@ window.__{SHORT_NAME}__PRODUCTION__CONF__ = {
"VITE_GLOB_API_URL": "",
"VITE_GLOB_API_URL_PREFIX": "/api",
"VITE_GLOB_FILE_URL": "http://file.django.elevue",
"VITE_GLOB_APP_TITLE": "Django+ElementPlus版",
"VITE_GLOB_APP_TITLE": "Django+AntDesign版",
// ...
};
Object.freeze(window.__{SHORT_NAME}__PRODUCTION__CONF__);
@@ -256,7 +256,7 @@ dist/
├── app.config.js # 运行时配置(VITE_GLOB_* 变量)
├── favicon.ico # 网站图标
└── assets/
├── index-[hash].js # 主包(Vue、ElementPlus、Pinia 等)
├── index-[hash].js # 主包(Vue、Ant Design Vue、Pinia 等)
├── index-[hash].css # 全局样式
├── [name]-[hash].js # 路由懒加载 chunk(按视图分割)
└── ... # 字体、图片等静态资源
@@ -283,7 +283,7 @@ Vite 自动将 `node_modules` 中的库分割为独立 chunk:
| chunk | 内容 |
|-------|------|
| `vendor-vue.js` | vue + vue-router + pinia |
| `vendor-element.js` | element-plus |
| `vendor-antd.js` | ant-design-vue |
| `vendor-echarts.js` | echarts(如果使用) |
| `vendor-*.js` | 其他大型依赖 |
@@ -293,7 +293,7 @@ Vite 自动将 `node_modules` 中的库分割为独立 chunk:
```typescript
optimizeDeps: {
include: ['dayjs', '@vicons/ionicons5', '@vicons/antd', '@element-plus/icons-vue'],
include: ['dayjs', '@ant-design/icons-vue'],
}
```
@@ -307,13 +307,8 @@ optimizeDeps: {
async function bootstrap() {
const app = createApp(App);
// 1. 全局注册 ElementPlus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
// 2. 全局引入 ElementPlus(中文包)
setupElement(app);
// 1. 全局注册 Ant Design Vue 组件
setupAntd(app);
// 3. 全局注册自定义组件(BasicTable、BasicForm 等)
setupCustomComponents(app);
@@ -339,7 +334,7 @@ async function bootstrap() {
| 注册项 | 文件 | 说明 |
|--------|------|------|
| ElementPlus | `element.ts` | 全局引入 + 中文包 |
| Ant Design Vue | `antdv.ts` | 全局引入组件 |
| 自定义组件 | `customComponents.ts` | BasicTable、BasicForm、PageWrapper 等 |
| 自定义指令 | `directives.ts` | `v-perm`、`v-perms`、`v-scrollBar` |
@@ -504,7 +499,7 @@ pnpm report
**优化手段**:
1. 路由懒加载(已默认启用)
2. 按需引入 ElementPlus 组件(当前为全量引入)
2. 按需引入 Ant Design Vue 组件(当前为全量引入)
3. 大型依赖(echarts、wangeditor)按需引入
4. 开启 gzip 压缩(`VITE_BUILD_COMPRESS=gzip`)
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
项目提供丰富的公共组件,位于 `ui/src/components/` 目录,基于 ElementPlus 二次封装,覆盖表格、表单、弹窗、上传、富文本编辑等常见场景。组件通过 `src/plugins/` 中的 `setupCustomComponents` 全局注册,任何页面直接使用,无需单独 import。
项目提供丰富的公共组件,位于 `ui/src/components/` 目录,基于 Ant Design Vue 二次封装,覆盖表格、表单、弹窗、上传、富文本编辑等常见场景。组件通过 `src/plugins/` 中的 `setupCustomComponents` 全局注册,任何页面直接使用,无需单独 import。
:::
## 组件总览
@@ -19,7 +19,7 @@
| CropperImage | `components/Cropper/` | 图片裁剪(圆形/矩形、实时预览) |
| QrCode | `components/Qrcode/` | 二维码生成(canvas/img、内嵌 logo) |
| ChinaArea | `components/ChinaArea/` | 省市区级联(懒加载、二/三级联动) |
| Icon | `components/icon/` | 图标(支持 ElementPlus 图标 + SVG 图标) |
| Icon | `components/icon/` | 图标(支持 Ant Design Icons + SVG 图标) |
| BasicSelect | `components/Select/` | 增强下拉(远程请求、本地缓存) |
| CountTo | `components/CountTo/` | 数字动画(前缀/后缀、千分位、缓动曲线) |
| Password | `components/Password/` | 密码强度(强度指示器、重复确认、复杂度校验) |
@@ -40,7 +40,7 @@
## BasicTable 表格
表格组件是使用频率最高的组件,基于 `el-table` + `el-pagination` 封装,详见 [BasicTable 表格](/zh/volume4/frontend/table) 章节。
表格组件是使用频率最高的组件,基于 Ant Design Vue 的 `a-table` 封装,详见 [BasicTable 表格](/zh/volume4/frontend/table) 章节。
### Props
@@ -79,12 +79,12 @@
| 属性 | 类型 | 说明 |
|------|------|------|
| `label` | `string` | 列标题 |
| `prop` | `string` | 字段名 |
| `title` | `string` | 列标题 |
| `dataIndex` | `string` | 字段名 |
| `width` | `number` | 列宽 |
| `align` | `string` | 对齐方式 |
| `type` | `string` | 类型:`index` / `selection` |
| `render` | `Function` | 自定义渲染函数 `(column, row, index) => VNode` |
| `customRender` | `Function` | 自定义渲染函数 `({ text, record, index, column }) => VNode` |
| `isSlot` | `boolean` | 是否使用插槽 |
| `ellipsis` | `boolean` | 超出省略(tooltip) |
| `auth` | `string[]` | 权限编码,控制列是否显示 |
@@ -131,37 +131,42 @@
<template>
<BasicTable :columns="columns" :request="loadDataTable" ref="tableRef">
<template #tableTitle>
<el-button v-perm="['sys:level:add']" type="primary" @click="handleAdd">
<el-icon><Plus /></el-icon>新增
</el-button>
<a-space>
<a-button v-perm="['sys:level:add']" type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template>
新增
</a-button>
</a-space>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-space>
<a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:level:update']">
<template #icon><EditOutlined /></template>
编辑
</a-button>
<a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:level:delete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</template>
</BasicTable>
</template>
<script setup lang="ts">
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
const columns = [
{ label: '名称', prop: 'name', width: 200 },
{ label: '状态', prop: 'status', width: 100 },
{ label: '创建时间', prop: 'createTime', width: 180 },
{ title: '名称', dataIndex: 'name', width: 200 },
{ title: '状态', dataIndex: 'status', width: 100 },
{ title: '创建时间', dataIndex: 'createTime', width: 180 },
];
const actionColumn = {
width: 200,
actions: [
{ label: '编辑', auth: ['sys:level:update'], onClick: handleEdit },
{
label: '删除',
auth: ['sys:level:delete'],
isConfirm: true,
popConfirm: { title: '确认删除?' },
onClick: handleDelete,
},
],
};
async function loadDataTable({ page, pageSize }) {
const res = await getListApi({ pageNo: page, pageSize });
return { items: res.data, total: res.count };
async function loadDataTable(params) {
const res = await getListApi(params);
return res;
}
</script>
```
@@ -228,7 +233,7 @@ async function loadDataTable({ page, pageSize }) {
| 属性 | 类型 | 说明 |
|------|------|------|
| `field` | `string` | 字段名(必填) |
| `name` | `string` | 字段名(必填) |
| `label` | `string` | 标签文字 |
| `component` | `ComponentType` | 渲染组件:`Input` / `Select` / `DatePicker` 等 |
| `componentProps` | `object` | 组件属性 |
@@ -270,13 +275,13 @@ async function loadDataTable({ page, pageSize }) {
const [registerForm] = useForm({
schemas: [
{
field: 'name',
name: 'name',
label: '名称',
component: 'Input',
componentProps: { placeholder: '请输入名称' },
},
{
field: 'status',
name: 'status',
label: '状态',
component: 'Select',
componentProps: {
@@ -287,7 +292,7 @@ const [registerForm] = useForm({
},
},
{
field: 'dateRange',
name: 'dateRange',
label: '日期范围',
component: 'DatePicker',
componentProps: { type: 'daterange' },
@@ -301,7 +306,7 @@ const [registerForm] = useForm({
## BasicModal 弹窗
弹窗组件基于 `el-dialog` 封装,支持拖拽、自定义按钮,详见 [Modal 弹窗](/zh/volume4/frontend/modal) 章节。
弹窗组件基于 `a-modal` 封装,支持拖拽、自定义按钮,详见 [Modal 弹窗](/zh/volume4/frontend/modal) 章节。
### Props
@@ -358,7 +363,7 @@ function handleEdit(record) {
## BasicUpload 上传
文件/图片上传组件,基于 `el-upload` 封装,支持卡片/列表模式、数量限制、图片预览。
文件/图片上传组件,基于 Ant Design Vue 的 `a-upload` 封装,支持卡片/列表模式、数量限制、图片预览。
### Props
@@ -700,10 +705,10 @@ async function getDeptOptions() {
<BasicTable :columns="columns" :request="loadData" />
<template #leftFooter>
<el-button @click="handleCancel">取消</el-button>
<a-button @click="handleCancel">取消</a-button>
</template>
<template #rightFooter>
<el-button type="primary" @click="handleSubmit">提交</el-button>
<a-button type="primary" @click="handleSubmit">提交</a-button>
</template>
</PageWrapper>
</template>
@@ -726,7 +731,7 @@ async function getDeptOptions() {
```vue
<template>
<Authority :value="['sys:user:add']">
<el-button type="primary">新增用户</el-button>
<a-button type="primary">新增用户</a-button>
</Authority>
</template>
```
@@ -734,7 +739,7 @@ async function getDeptOptions() {
:::tip v-perm 指令
除了 `Authority` 组件,项目还提供 `v-perm` 指令,功能相同但更简洁:
```vue
<el-button v-perm="['sys:user:add']">新增用户</el-button>
<a-button v-perm="['sys:user:add']">新增用户</a-button>
```
:::
@@ -742,7 +747,7 @@ async function getDeptOptions() {
## Icon 图标
统一图标组件,支持 ElementPlus 图标和 SVG 图标。
统一图标组件,支持 Ant Design Icons 和 SVG 图标。
### Props
@@ -756,8 +761,8 @@ async function getDeptOptions() {
```vue
<template>
<!-- ElementPlus 图标 -->
<Icon name="el-icon-Plus" size="18px" />
<!-- Ant Design Icons -->
<PlusOutlined style="font-size: 18px" />
<!-- SVG 图标 -->
<Icon name="svg-icon-user" />
</template>
@@ -838,4 +843,4 @@ setupCustomComponents(app); // 注册所有自定义组件
## 总结
公共组件库基于 ElementPlus 二次封装,核心三件套 BasicTable(表格)、BasicForm(表单)、BasicModal(弹窗)覆盖列表页标准场景。辅以 Upload、Editor、Cropper 等业务组件,以及 Authority、v-perm 权限体系。通过全局注册,任何页面直接使用,无需单独 import。优先使用公共组件,避免重复开发。
公共组件库基于 Ant Design Vue 二次封装,核心三件套 BasicTable(表格)、BasicForm(表单)、BasicModal(弹窗)覆盖列表页标准场景。辅以 Upload、Editor、Cropper 等业务组件,以及 Authority、v-perm 权限体系。通过全局注册,任何页面直接使用,无需单独 import。优先使用公共组件,避免重复开发。
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
`BasicForm` 位于 `src/components/Form/src/BasicForm.vue`,基于 ElementPlus 的 `el-form` 二次封装,通过 schemas 配置化定义表单字段,支持查询表单和业务表单两种模式。
`BasicForm` 位于 `src/components/Form/src/BasicForm.vue`,基于 Ant Design Vue 的 `a-form` 二次封装,通过 schemas 配置化定义表单字段,支持查询表单和业务表单两种模式。
:::
## 组件架构
@@ -26,9 +26,9 @@ src/components/Form/
列表页的搜索区域使用 `useForm` 注册表单:
```vue
<el-card :bordered="false" class="pt-3 mb-3 proCard">
<a-card :bordered="false" class="pt-3 mb-3 proCard">
<BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
</el-card>
</a-card>
```
### querySchemas 定义
@@ -40,7 +40,7 @@ import { FormSchema } from '@/components/Form/index';
export const schemas: FormSchema[] = [
{
field: 'name',
name: 'name',
component: 'Input',
label: '岗位名称',
componentProps: {
@@ -48,12 +48,13 @@ export const schemas: FormSchema[] = [
},
},
{
field: 'status',
name: 'status',
component: 'Select',
label: '状态',
componentProps: {
placeholder: '请选择状态',
clearable: true,
allowClear: true,
options: [
{ label: '正常', value: '1' },
{ label: '禁用', value: '2' },
@@ -68,15 +69,19 @@ export const schemas: FormSchema[] = [
```typescript
import { schemas } from './querySchemas';
import { useForm } from '@/components/Form/index';
import { ColProps } from 'element-plus';
const formParams = reactive({ name: '', status: '' });
const [register, {}] = useForm({
labelWidth: 80,
layout: 'horizontal',
colProps: { span: 6 } as ColProps,
submitOnReset: true,
rowProps: { gutter: [16, 0] },
colProps: {
xs: 24,
sm: 24,
md: 12,
lg: 8,
xl: 6,
},
labelCol: { span: 6, offset: 0 },
schemas,
});
@@ -95,73 +100,73 @@ function handleReset() {
## 业务表单(编辑弹窗)
编辑弹窗中直接使用 `el-form` + `el-form-item` 构建表单:
编辑弹窗中直接使用 `a-form` + `a-form-item` 构建表单:
```vue
<!-- src/views/system/position/edit.vue -->
<template>
<el-dialog v-model="props.visible" :title="props.positionId ? '编辑' : '新增'" width="500">
<el-form class="ls-form" ref="formRef" :model="formData" label-width="80px">
<el-form-item
<a-modal v-model:visible="props.visible" :title="props.positionId ? '编辑' : '新增'" width="500px" @cancel="dialogClose">
<a-form class="ls-form" ref="formRef" :model="formData" :label-col="{ style: { width: '85px' } }">
<a-form-item
label="岗位名称"
prop="name"
name="name"
:rules="{ required: true, message: '请输入岗位名称', trigger: 'blur' }"
>
<el-input v-model="formData.name" placeholder="请输入岗位名称" clearable />
</el-form-item>
<el-form-item label="岗位状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio :value="1">正常</el-radio>
<el-radio :value="2">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="排序" prop="sort">
<el-input-number v-model="formData.sort" />
</el-form-item>
</el-form>
</el-dialog>
<a-input v-model:value="formData.name" placeholder="请输入岗位名称" allow-clear />
</a-form-item>
<a-form-item label="岗位状态" name="status">
<a-radio-group v-model:value="formData.status" name="status">
<a-radio :value="1">正常</a-radio>
<a-radio :value="2">停用</a-radio>
</a-radio-group>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" />
</a-form-item>
</a-form>
</a-modal>
</template>
```
## BasicForm 内部渲染机制
`BasicForm.vue` 根据 `schema.component` 动态渲染对应的 ElementPlus 组件:
`BasicForm.vue` 根据 `schema.component` 动态渲染对应的 Ant Design Vue 组件:
```vue
<!-- src/components/Form/src/BasicForm.vue 核心逻辑 -->
<template v-for="schema in getSchema" :key="schema.field">
<template v-for="schema in getSchema" :key="schema.name">
<!-- Checkbox -->
<template v-if="schema.component === 'Checkbox'">
<el-checkbox-group v-model="formModel[schema.field]">
<el-checkbox v-for="item in schema.componentProps?.options" :value="item.value">
{{ item.label }}
</el-checkbox>
</el-checkbox-group>
<a-checkbox-group v-bind="getSpecComponentProps(schema)" v-model:value="formModel[schema.name]">
<a-space>
<a-checkbox v-for="item in schema.componentProps?.options" :key="item.value" :value="item.value" :label="item.label" />
</a-space>
</a-checkbox-group>
</template>
<!-- RadioGroup -->
<template v-else-if="schema.component === 'RadioGroup'">
<el-radio-group v-model="formModel[schema.field]">
<el-radio v-for="item in schema.componentProps?.options" :value="item.value">
{{ item.label }}
</el-radio>
</el-radio-group>
<a-radio-group v-bind="getSpecComponentProps(schema)" v-model:value="formModel[schema.name]">
<a-space>
<a-radio v-for="item in schema.componentProps?.options" :key="item.value" :value="item.value">
{{ item.label }}
</a-radio>
</a-space>
</a-radio-group>
</template>
<!-- Select -->
<template v-else-if="schema.component === 'Select'">
<el-select v-model="formModel[schema.field]">
<el-option v-for="item in schema.componentProps?.options" :value="item.value" :label="item.label" />
</el-select>
<!-- BasicSelect -->
<template v-else-if="schema.component === 'BasicSelect'">
<BasicSelect v-model:value="formModel[schema.name]" v-bind="schema.componentProps" />
</template>
<!-- Daterange -->
<template v-else-if="schema.component === 'Daterange'">
<el-date-picker v-model="formModel[schema.field]" type="daterange" value-format="YYYY-MM-DD" />
</template>
<!-- 其他组件:动态渲染 el-{component} -->
<component v-else :is="`el-${schema.component}`" v-model="formModel[schema.field]" />
<!-- 其他组件:动态渲染 a-{component} -->
<component
v-else
v-bind="getComponentProps(schema)"
:is="`a-${schema.component}`"
v-model:value="formModel[schema.name]"
/>
</template>
```
@@ -169,10 +174,10 @@ function handleReset() {
```typescript
interface FormSchema {
field: string; // 字段名
name: string; // 字段名
label: string; // 标签文本
component: string; // 组件类型:Input / Select / RadioGroup / Checkbox / DatePicker 等
componentProps?: any; // 组件属性(placeholder、options、clearable 等)
componentProps?: any; // 组件属性(placeholder、options、allowClear 等)
required?: boolean; // 是否必填
rules?: any[]; // 自定义校验规则
defaultValue?: any; // 默认值
@@ -202,7 +207,7 @@ Schema 中的 `required: true` 会自动生成必填校验规则,也可以通
```typescript
{
field: 'name',
name: 'name',
label: '岗位名称',
component: 'Input',
rules: [
@@ -239,4 +244,4 @@ onMounted(() => {
## 总结
BasicForm 通过 schemas 配置化定义表单字段,内部根据 `component` 动态渲染对应的 ElementPlus 组件。查询表单使用 `useForm` 注册并绑定 `@submit`/`@reset` 事件,业务表单直接使用 `el-form` + `reactive` 管理数据。支持多种组件类型、表单校验、数据绑定、条件隐藏等能力。
BasicForm 通过 schemas 配置化定义表单字段,内部根据 `component` 动态渲染对应的 Ant Design Vue 组件。查询表单使用 `useForm` 注册并绑定 `@submit`/`@reset` 事件,业务表单直接使用 `a-form` + `reactive` 管理数据。支持多种组件类型、表单校验、数据绑定、条件隐藏等能力。
@@ -132,7 +132,7 @@ const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);
```
```vue
<el-button :loading="subLoading" type="primary" @click="submit">确定</el-button>
<a-button :loading="subLoading" type="primary" @click="submit">确定</a-button>
```
## useAsync
@@ -3,39 +3,36 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
当前项目仅支持中文界面,ElementPlus 使用中文语言包(`zh-cn`),所有界面文本直接硬编码在组件中。如需扩展多语言支持,可基于 vue-i18n 实现。
当前项目仅支持中文界面,Ant Design Vue 默认支持中文,所有界面文本直接硬编码在组件中。如需扩展多语言支持,可基于 vue-i18n 实现。
:::
## 当前状态
项目当前为中文单语言版本:
- ElementPlus 全局配置中文语言包:`app.use(ElementPlus, { locale: zhCn })`
- 所有界面文本直接硬编码在组件中:`<el-button>添加岗位</el-button>`
- Ant Design Vue 默认支持中文,无需额外配置语言包
- 所有界面文本直接硬编码在组件中:`<a-button>添加岗位</a-button>`
- 后端返回的 `msg` 字段为中文:`"操作成功"`、`"岗位名称不能重复"`
```vue
<template>
<el-button type="primary">添加岗位</el-button>
<el-table-column label="岗位名称" prop="name" />
<el-table-column label="创建时间" prop="createTime" />
<a-button type="primary">添加岗位</a-button>
<!-- 表格列通过 columns.ts 配置 -->
</template>
```
## ElementPlus 中文配置
## Ant Design Vue 中文配置
项目在入口文件中全局配置 ElementPlus 中文语言包:
Ant Design Vue 默认支持中文,无需额外配置。如需切换语言,可通过 ConfigProvider 设置:
```typescript
// main.ts
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
app.use(ElementPlus, { locale: zhCn });
```vue
<template>
<a-config-provider :locale="zhCN">
<App />
</a-config-provider>
</template>
```
配置后,ElementPlus 组件的默认文本(如分页、日期选择器、表格空数据等)自动显示中文。
## 扩展方案
如需支持多语言,推荐使用 vue-i18n:
@@ -126,8 +123,8 @@ export default i18n;
```vue
<template>
<el-button type="primary">{{ $t('common.add') }}</el-button>
<el-table-column :label="$t('position.name')" prop="name" />
<a-button type="primary">{{ $t('common.add') }}</a-button>
<!-- 表格列通过 columns.ts 配置 -->
</template>
<script setup>
@@ -136,12 +133,12 @@ const { t } = useI18n();
</script>
```
### ElementPlus 国际化联动
### Ant Design Vue 国际化联动
```typescript
// 动态切换 ElementPlus 语言
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import en from 'element-plus/es/locale/lang/en';
// 动态切换 Ant Design Vue 语言
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import enUS from 'ant-design-vue/es/locale/en_US';
const locale = computed(() => {
return i18n.global.locale.value === 'zh-CN' ? zhCn : en;
@@ -150,9 +147,9 @@ const locale = computed(() => {
```vue
<template>
<el-config-provider :locale="locale">
<a-config-provider :locale="locale">
<App />
</el-config-provider>
</a-config-provider>
</template>
```
@@ -163,7 +160,7 @@ const locale = computed(() => {
function changeLanguage(lang: string) {
i18n.global.locale.value = lang;
localStorage.setItem('lang', lang);
// 同步切换 ElementPlus 语言
// 同步切换 Ant Design Vue 语言
}
```
@@ -206,7 +203,7 @@ const errorMap = {
```
:::warning 注意事项
1. ElementPlus 内置组件的文本(如"暂无数据"、"请选择")通过 `locale` 属性自动切换
1. Ant Design Vue 内置组件的文本(如"暂无数据"、"请选择")通过 `locale` 属性自动切换
2. 后端返回的 `msg` 字段需要额外处理
3. 日期格式、数字格式也需要考虑国际化
:::
@@ -227,4 +224,4 @@ const errorMap = {
## 总结
当前项目为中文单语言版本,ElementPlus 使用中文语言包。如需扩展多语言支持,可基于 vue-i18n 实现前端国际化,配合 ElementPlus 内置语言包和后端消息 code 实现全链路多语言。改造需考虑前端文本、ElementPlus 组件、后端消息三个维度的国际化。
当前项目为中文单语言版本,Ant Design Vue 默认支持中文。如需扩展多语言支持,可基于 vue-i18n 实现前端国际化,配合 Ant Design Vue 内置语言包和后端消息 code 实现全链路多语言。改造需考虑前端文本、Ant Design Vue 组件、后端消息三个维度的国际化。
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
项目提供 `BasicModal` 组件(`src/components/Modal/src/BasicModal.vue`)和原生 `el-dialog` 两种弹窗用法。编辑弹窗通过 `defineAsyncComponent` 懒加载,减少首屏渲染负担。
项目提供 `BasicModal` 组件(`src/components/Modal/src/basicModal.vue`)和原生 `a-modal` 两种弹窗用法。编辑弹窗通过 `defineAsyncComponent` 懒加载,减少首屏渲染负担。
:::
## 组件架构
@@ -11,20 +11,24 @@
```
src/components/Modal/
├── src/
│ ├── BasicModal.vue # 主组件(基于 el-dialog)
│ ├── basicModal.vue # 主组件(基于 a-modal)
│ ├── props.ts # 属性定义
│ ├── type.ts # 类型定义(ModalProps、ModalMethods)
│ └── hooks/
│ └── useModalContext.ts # 弹窗上下文
│ ├── type/index.ts # 类型定义(ModalProps、ModalMethods)
│ ├── hooks/
│ │ ├── useModal.ts # 弹窗 Hook
│ │ └── useModalDrag.ts # 弹窗拖拽
│ └── components/
│ ├── Modal.tsx # 弹窗渲染组件
│ └── ModalClose.vue # 关闭按钮组件
└── index.ts # 导出 useModal 等
```
## BasicModal 组件
`BasicModal` 基于 `el-dialog` 封装,提供全屏切换、自定义头部、提交按钮等能力:
`BasicModal` 基于 `a-modal` 封装,提供全屏切换、自定义头部、提交按钮等能力:
```vue
<BasicModal :title="'编辑'" :width="600" @register="registerModal" @ok="handleSubmit">
<BasicModal title="编辑" :width="600" @register="registerModal" @ok="handleSubmit">
<BasicForm @register="registerForm" />
</BasicModal>
```
@@ -38,7 +42,7 @@ src/components/Modal/
## 实际用法(position 模块)
以岗位管理为例,实际使用原生 `el-dialog` + `defineAsyncComponent` 懒加载:
以岗位管理为例,实际使用原生 `a-modal` + `defineAsyncComponent` 懒加载:
### 父组件(index.vue)
@@ -59,8 +63,8 @@ const handleAdd = async () => {
};
// 编辑
const handleEdit = async (record: Recordable) => {
positionId.value = record.row.id;
const handleEdit = async (id: number) => {
positionId.value = id;
await nextTick();
editVisible.value = true;
};
@@ -83,41 +87,44 @@ const handleEdit = async (record: Recordable) => {
```vue
<!-- src/views/system/position/edit.vue -->
<template>
<el-dialog
v-model="props.visible"
<a-modal
v-model:visible="props.visible"
:title="props.positionId ? '编辑' : '新增'"
width="500"
:close-on-click-modal="false"
:before-close="dialogClose"
width="500px"
@cancel="dialogClose"
>
<el-form class="ls-form" ref="formRef" :model="formData" label-width="80px">
<el-form-item
<a-form class="ls-form" ref="formRef" :model="formData" :label-col="{ style: { width: '85px' } }">
<a-form-item
label="岗位名称"
prop="name"
name="name"
:rules="{ required: true, message: '请输入岗位名称', trigger: 'blur' }"
>
<el-input v-model="formData.name" placeholder="请输入岗位名称" clearable />
</el-form-item>
<el-form-item label="岗位状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio :value="1">正常</el-radio>
<el-radio :value="2">停用</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="排序" prop="sort">
<el-input-number v-model="formData.sort" />
</el-form-item>
</el-form>
<a-input v-model:value="formData.name" placeholder="请输入岗位名称" allow-clear />
</a-form-item>
<a-form-item label="岗位状态" name="status">
<a-radio-group v-model:value="formData.status" name="status">
<a-radio :value="1">正常</a-radio>
<a-radio :value="2">停用</a-radio>
</a-radio-group>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" />
</a-form-item>
</a-form>
<template #footer>
<el-button @click="dialogClose">取消</el-button>
<el-button :loading="subLoading" type="primary" @click="submit">确定</el-button>
<span class="dialog-footer">
<a-button @click="dialogClose">取消</a-button>
<a-button :loading="subLoading" type="primary" @click="submit">确定</a-button>
</span>
</template>
</el-dialog>
</a-modal>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import { getPositionDetail, positionAdd, positionUpdate } from '@/api/system/position';
import { useLockFn } from '@/utils/useLockFn';
import { message } from 'ant-design-vue';
const emit = defineEmits(['success', 'update:visible']);
const formRef = shallowRef<FormInstance>();
@@ -133,7 +140,7 @@ const props = defineProps({
const handleSubmit = async () => {
await formRef.value?.validate();
props.positionId ? await positionUpdate(formData) : await positionAdd(formData);
message('操作成功');
message.success('操作成功');
emit('update:visible', false);
emit('success');
};
@@ -163,7 +170,7 @@ onMounted(() => {
## 弹窗数据流
```
父组件点击编辑 → positionId = record.row.id → editVisible = true
父组件点击编辑 → positionId = id → editVisible = true
↓
edit.vue onMounted → positionId != 0 → setFormData() → 获取详情填充表单
↓
@@ -174,25 +181,30 @@ emit('success') → 父组件 reloadTable() → 表格刷新
## 确认弹窗
删除等危险操作使用 `confirm` 封装函数(来自 `src/utils/auth.ts`):
删除等危险操作使用 Ant Design Vue 的 `Modal.confirm`:
```typescript
import { message, confirm } from '@/utils/auth';
import { Modal, message } from 'ant-design-vue';
async function handleDelete(record: Recordable) {
async function handleDelete(id) {
let ids = [];
if (!record) {
if (!id) {
ids = selectionData.value.map(({ id }) => id);
}
await confirm('确定要删除?');
record ? await positionDelete(record.row.id) : await positionBatchDelete(ids);
message('删除成功');
reloadTable();
Modal.confirm({
title: '提示',
content: '确定要删除?',
onOk: async () => {
id ? await positionDelete(id) : await positionBatchDelete(ids);
message.success('删除成功');
reloadTable();
},
});
}
```
`confirm` 内部调用 `ElMessageBox.confirm`,返回 Promise,用户取消时抛出异常中断后续逻辑。
`Modal.confirm` 返回一个引用,用户点击取消时不会执行 `onOk` 回调。
## v-model:visible 双向绑定
@@ -215,4 +227,4 @@ const dialogClose = () => { emit('update:visible', false); };
## 总结
编辑弹窗使用 `el-dialog` + `defineAsyncComponent` 懒加载,通过 `v-model:visible` 双向绑定显隐状态,`useLockFn` 防重复提交。父组件通过 `positionId` prop 传递编辑行 ID,子组件在 `onMounted` 中判断并加载详情数据。操作成功后 `emit('success')` 通知父组件刷新表格。
编辑弹窗使用 `a-modal` + `defineAsyncComponent` 懒加载,通过 `v-model:visible` 双向绑定显隐状态,`useLockFn` 防重复提交。父组件通过 `positionId` prop 传递编辑行 ID,子组件在 `onMounted` 中判断并加载详情数据。操作成功后 `emit('success')` 通知父组件刷新表格。确认弹窗使用 Ant Design Vue 的 `Modal.confirm`。
@@ -92,15 +92,15 @@ export function usePermission() {
### v-perm(满足任一权限)
```vue
<el-button v-perm="['sys:position:add']">添加岗位</el-button>
<el-button v-perm="['sys:position:batchDelete']">删除</el-button>
<el-button v-perm="['sys:position:export']">导出</el-button>
<a-button v-perm="['sys:position:add']">添加岗位</a-button>
<a-button v-perm="['sys:position:batchDelete']">删除</a-button>
<a-button v-perm="['sys:position:export']">导出</a-button>
```
### v-perms(满足所有权限)
```vue
<el-button v-perms="['sys:user:add', 'sys:user:import']">高级操作</el-button>
<a-button v-perms="['sys:user:add', 'sys:user:import']">高级操作</a-button>
```
### 与 v-if 结合
@@ -115,7 +115,7 @@ const showAddBtn = computed(() => hasPermission(['sys:position:add']));
```
```vue
<el-button v-if="showAddBtn">添加岗位</el-button>
<a-button v-if="showAddBtn">添加岗位</a-button>
```
## 实际用法(position 模块)
@@ -125,51 +125,41 @@ const showAddBtn = computed(() => hasPermission(['sys:position:add']));
```vue
<!-- src/views/system/position/index.vue -->
<template>
<BasicTable :columns="columns" :request="loadDataTable" ref="tableRef" :actionColumn="actionColumn">
<BasicTable :columns="columns" :request="loadDataTable" ref="tableRef" :row-selection="{ onChange: onSelectionChange }">
<template #tableTitle>
<el-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
<template #icon><el-icon><PlusOutlined /></el-icon></template>
添加岗位
</el-button>
<el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length"
v-perm="['sys:position:batchDelete']">
<template #icon><el-icon><Delete /></el-icon></template>
删除
</el-button>
<a-space>
<a-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
<template #icon><PlusOutlined /></template>
添加岗位
</a-button>
<a-button type="danger" @click="handleDelete()" :disabled="!selectionData.length"
v-perm="['sys:position:batchDelete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</BasicTable>
</template>
```
操作列中的权限控制通过 `auth` 属性实现:
操作列中的权限控制通过 `bodyCell` 插槽 + `v-perm` 指令实现:
```typescript
const actionColumn = reactive({
width: 200,
label: '操作',
fixed: 'right',
render(record) {
return h(TableAction, {
style: 'button',
actions: [
{
label: '编辑',
icon: 'Edit',
type: 'warning',
onClick: handleEdit.bind(null, record),
auth: ['sys:position:update'], // 权限节点
},
{
label: '删除',
icon: 'Delete',
type: 'danger',
onClick: handleDelete.bind(null, record),
auth: ['sys:position:delete'], // 权限节点
},
],
});
},
});
```vue
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-space>
<a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:position:update']">
<template #icon><EditOutlined /></template>
编辑
</a-button>
<a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:position:delete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</template>
```
## 权限节点命名规范
@@ -206,7 +196,7 @@ class ExampleAddView(PermissionRequired, View):
```vue
<!-- 前端 -->
<el-button v-perm="['sys:example:add']">添加案例</el-button>
<a-button v-perm="['sys:example:add']">添加案例</a-button>
```
## 超级管理员
@@ -228,4 +218,4 @@ setupDirectives(app); // 注册 v-perm、v-perms 等指令
## 总结
`v-perm`(满足任一权限)和 `v-perms`(满足所有权限)指令通过 `usePermission` Hook 检查用户权限列表,无权限时自动从 DOM 移除元素。操作列通过 `TableAction` 组件的 `auth` 属性控制。权限节点在菜单管理中配置,需要保持前后端字符串完全一致。`*:*:*` 通配符表示超级管理员。
`v-perm`(满足任一权限)和 `v-perms`(满足所有权限)指令通过 `usePermission` Hook 检查用户权限列表,无权限时自动从 DOM 移除元素。操作列通过 `bodyCell` 插槽 + `v-perm` 指令控制。权限节点在菜单管理中配置,需要保持前后端字符串完全一致。`*:*:*` 通配符表示超级管理员。
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
前端基于 Vue3 + ElementPlus 构建,使用 pnpm 作为包管理工具,Vite 作为构建工具,TypeScript 作为开发语言。
前端基于 Vue3 + Ant Design Vue 构建,使用 pnpm 作为包管理工具,Vite 作为构建工具,TypeScript 作为开发语言。
:::
## 技术栈
@@ -11,7 +11,7 @@
| 技术 | 版本 | 说明 |
|------|------|------|
| Vue | 3.x | 渐进式 JavaScript 框架,组合式 API |
| ElementPlus | 2.x | Vue3 组件库 |
| Ant Design Vue | 3.x | Vue3 组件库 |
| Vite | 3.x | 下一代前端构建工具 |
| Pinia | 2.x | 状态管理(Vuex 替代方案) |
| Vue Router | 4.x | 路由管理 |
@@ -152,7 +152,7 @@ import { setupElement, setupDirectives, setupCustomComponents } from '@/plugins'
async function bootstrap() {
const app = createApp(App);
setupElement(app); // 全局引入 ElementPlus 组件
setupAntd(app); // 全局引入 Ant Design Vue 组件
setupCustomComponents(app); // 注册自定义组件
setupDirectives(app); // 注册自定义指令(v-perm 等)
setupStore(app); // 挂载 Pinia 状态管理
@@ -165,8 +165,8 @@ async function bootstrap() {
void bootstrap();
```
初始化顺序:样式加载 -> ElementPlus -> 自定义组件 -> 自定义指令 -> Pinia Store -> Router -> 挂载。
初始化顺序:样式加载 -> Ant Design Vue -> 自定义组件 -> 自定义指令 -> Pinia Store -> Router -> 挂载。
## 总结
前端项目基于 Vue3 + ElementPlus + Vite + TypeScript + Pinia 构建,使用 pnpm 管理依赖,Tailwind CSS + SCSS 提供样式能力。通过 `main.ts` 的 `bootstrap()` 函数按顺序初始化所有基础设施,目录结构按功能分层组织,便于维护和扩展。
前端项目基于 Vue3 + Ant Design Vue + Vite + TypeScript + Pinia 构建,使用 pnpm 管理依赖,Tailwind CSS + SCSS 提供样式能力。通过 `main.ts` 的 `bootstrap()` 函数按顺序初始化所有基础设施,目录结构按功能分层组织,便于维护和扩展。
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
前端样式方案采用 Tailwind CSS + SCSS + ElementPlus 主题覆盖,支持深色模式切换。全局 SCSS 变量通过 Vite 的 `additionalData` 注入。
前端样式方案采用 Tailwind CSS + SCSS + Ant Design Vue 主题覆盖,支持深色模式切换。全局 SCSS 变量通过 Vite 的 `additionalData` 注入。
:::
## 样式架构
@@ -13,7 +13,7 @@ src/styles/
├── var.scss # SCSS 全局变量(通过 Vite additionalData 注入)
├── index.scss # 入口文件,引入所有样式
├── tailwindbase.css # Tailwind CSS 基础样式
└── element-override.css # ElementPlus 主题覆盖(可选)
└── antd-override.css # Ant Design Vue 主题覆盖(可选)
```
## SCSS 全局变量
@@ -58,36 +58,27 @@ import './styles/tailwindbase.css';
<div class="w-full md:w-1/2 lg:w-1/3">响应式宽度</div>
```
## ElementPlus 主题
## Ant Design Vue 主题
ElementPlus 通过 CSS 变量支持主题定制:
Ant Design Vue 通过 CSS 变量和 ConfigProvider 支持主题定制:
```typescript
// main.ts
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/display.css';
import 'element-plus/theme-chalk/dark/css-vars.css'; // 深色模式 CSS 变量
```
// src/plugins/antdv.ts
import { Button, Form, Table, Modal, message } from 'ant-design-vue';
### ElementPlus 全局引入
```typescript
// src/plugins/setupElement.ts
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
export function setupElement(app) {
app.use(ElementPlus, { locale: zhCn, size: 'default' });
export function setupAntd(app) {
app.use(Button).use(Form).use(Table).use(Modal);
// ... 其他组件注册
}
```
## 深色模式
通过 ElementPlus 的 `dark/css-vars.css` 和 Tailwind 的 `dark` 模式实现深色主题:
通过 Tailwind 的 `dark` 模式和 Ant Design Vue 的 ConfigProvider 实现深色主题:
```vue
<template>
<el-switch v-model="isDark" @change="toggleDark" />
<a-switch v-model:checked="isDark" @change="toggleDark" />
</template>
<script setup>
@@ -98,15 +89,7 @@ const toggleDark = (val) => {
</script>
```
深色模式样式:
```css
.dark {
--el-bg-color: #1d1e1f;
--el-text-color-primary: #e5eaf3;
--el-border-color: #4c4d4f;
}
```
深色模式样式通过 Ant Design Vue 的主题算法自动处理,也可通过 CSS 变量自定义。
## 设计配置 Store
@@ -132,12 +115,12 @@ export function useDesignSetting() {
```vue
<template>
<PageWrapper>
<el-card :bordered="false" class="pt-3 mb-3 proCard">
<a-card :bordered="false" class="pt-3 mb-3 proCard">
<!-- 搜索区域 -->
</el-card>
<el-card :bordered="false" class="proCard">
</a-card>
<a-card :bordered="false" class="proCard">
<!-- 表格区域 -->
</el-card>
</a-card>
</PageWrapper>
</template>
```
@@ -152,4 +135,4 @@ export function useDesignSetting() {
## 总结
样式方案采用 Tailwind CSS 提供原子化样式 + SCSS 全局变量(Vite `additionalData` 注入)+ ElementPlus 主题覆盖,支持深色模式切换。`designSetting` store 管理主题配置,`PageWrapper` 组件提供统一页面容器。
样式方案采用 Tailwind CSS 提供原子化样式 + SCSS 全局变量(Vite `additionalData` 注入)+ Ant Design Vue 主题覆盖,支持深色模式切换。`designSetting` store 管理主题配置,`PageWrapper` 组件提供统一页面容器。
@@ -3,7 +3,7 @@
<!-- Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 -->
:::tip 说明
`BasicTable` 位于 `src/components/Table/src/Table.vue`,基于 ElementPlus 的 `el-table` 二次封装,提供列定义、数据请求、分页、操作列、多选、全屏、密度调整、列设置等能力。
`BasicTable` 位于 `src/components/Table/src/Table.vue`,基于 Ant Design Vue 的 `a-table` 二次封装,提供列定义、数据请求、分页、操作列、多选、全屏、密度调整、列设置等能力。
:::
## 组件架构
@@ -36,44 +36,98 @@ src/components/Table/
:request="loadDataTable"
:row-key="(row) => row.id"
ref="tableRef"
:actionColumn="actionColumn"
@selection-change="onSelectionChange"
:row-selection="{ onChange: onSelectionChange }"
scroll-x="1200"
>
<template #tableTitle>
<el-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">添加岗位</el-button>
<a-space>
<a-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
<template #icon><PlusOutlined /></template>
新建
</a-button>
<a-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:position:batchDelete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-space>
<a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:position:update']">
<template #icon><EditOutlined /></template>
编辑
</a-button>
<a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:position:delete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</template>
</BasicTable>
```
## 列定义
`columns` 定义表格列,支持 `render` 函数自定义渲染:
`columns` 定义表格列,支持 `customRender` 函数自定义渲染:
```typescript
// src/views/system/position/columns.ts
import { h } from 'vue';
import { ElTag } from 'element-plus';
import { Tag } from 'ant-design-vue';
export const columns = [
{ type: 'selection' },
{ label: 'ID', prop: 'id', fixed: 'left', width: 50 },
{ label: '岗位名称', prop: 'name', minWidth: 100 },
{
label: '岗位状态',
prop: 'status',
minWidth: 100,
render(record) {
title: 'ID',
dataIndex: 'id',
fixed: 'left',
width: 50,
},
{
title: '岗位名称',
dataIndex: 'name',
width: 100,
},
{
title: '岗位状态',
dataIndex: 'status',
width: 100,
customRender({ record }) {
return h(
ElTag,
{ type: record.row.status == 1 ? 'success' : 'danger' },
{ default: () => (record.row.status == 1 ? '正常' : '停用') },
Tag,
{
color: record.status == 1 ? 'success' : 'error',
},
{
default: () => (record.status == 1 ? '正常' : '停用'),
},
);
},
},
{ label: '排序', prop: 'sort', minWidth: 100 },
{ label: '创建人', prop: 'createUser', minWidth: 100 },
{ label: '创建时间', prop: 'createTime', width: 180 },
{
title: '排序',
dataIndex: 'sort',
width: 100,
},
{
title: '创建人',
dataIndex: 'createUser',
width: 100,
},
{
title: '创建时间',
dataIndex: 'createTime',
width: 180,
},
{
title: '操作',
fixed: 'right',
dataIndex: 'action',
key: 'action',
width: 200,
},
];
```
@@ -81,18 +135,14 @@ export const columns = [
| 属性 | 类型 | 说明 |
|------|------|------|
| `prop` | string | 字段名 |
| `label` | string | 列标题 |
| `dataIndex` | string | 字段名 |
| `title` | string | 列标题 |
| `width` | number | 固定宽度 |
| `minWidth` | number | 最小宽度 |
| `type` | string | 列类型:`selection` / `index` |
| `fixed` | string | 固定列:`left` / `right` |
| `render` | function | 自定义渲染函数,接收 `{ row, column, index }` |
| `isSlot` | boolean | 是否使用插槽渲染 |
| `customRender` | function | 自定义渲染函数,接收 `{ text, record, index, column }` |
| `key` | string | 列的唯一标识(操作列必须设置) |
| `ellipsis` | boolean | 是否溢出省略 |
`render` 函数中 `record.row` 是行数据,`record.$index` 是行索引。
## 数据请求
`request` 属性传入数据请求函数,组件自动管理分页和 loading:
@@ -100,7 +150,7 @@ export const columns = [
```typescript
const loadDataTable = async (res: any) => {
const result = await getPositionList({ ...formParams, ...res });
return result; // 返回 { data, count } 结构
return result; // 返回 { records, total, size, current, pages } 结构
};
```
@@ -108,64 +158,60 @@ const loadDataTable = async (res: any) => {
## 操作列
`actionColumn` 使用 `TableAction` 组件渲染行操作按钮,支持权限控制:
Ant Design Vue 版本使用 `bodyCell` 插槽渲染行操作按钮,支持权限控制:
```typescript
import { TableAction } from '@/components/Table';
const actionColumn = reactive({
width: 200,
label: '操作',
prop: 'action',
fixed: 'right',
render(record) {
return h(TableAction, {
style: 'button',
actions: [
{
label: '编辑',
icon: 'Edit',
type: 'warning',
onClick: handleEdit.bind(null, record),
auth: ['sys:position:update'], // 权限节点
},
{
label: '删除',
icon: 'Delete',
type: 'danger',
onClick: handleDelete.bind(null, record),
auth: ['sys:position:delete'], // 权限节点
},
],
});
},
});
```vue
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-space>
<a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:position:update']">
<template #icon><EditOutlined /></template>
编辑
</a-button>
<a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:position:delete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</template>
```
`TableAction` 的 `auth` 属性接受权限数组,内部通过 `usePermission` Hook 检查,无权限时自动隐藏按钮。
按钮通过 `v-perm` 指令控制权限,无权限时自动隐藏。
## 多选
通过 `selection-change` 事件获取选中行:
通过 `row-selection` 属性配置多选,使用 `onChange` 回调获取选中行:
```vue
<BasicTable
:row-selection="{ onChange: onSelectionChange }"
/>
```
```typescript
const selectionData = ref([]);
function onSelectionChange(value) {
selectionData.value = value;
function onSelectionChange(selectedRowKeys, selectedRows) {
selectionData.value = selectedRows;
}
// 批量删除
async function handleDelete(record) {
async function handleDelete(id) {
let ids = [];
if (!record) {
if (!id) {
ids = selectionData.value.map(({ id }) => id);
}
await confirm('确定要删除?');
record ? await positionDelete(record.row.id) : await positionBatchDelete(ids);
message('删除成功');
reloadTable();
Modal.confirm({
title: '提示',
content: '确定要删除?',
onOk: async () => {
id ? await positionDelete(id) : await positionBatchDelete(ids);
message.success('删除成功');
reloadTable();
},
});
}
```
@@ -184,7 +230,7 @@ function reloadTable(noRefresh = '') {
// 操作成功后刷新
const handleAdd = async () => {
await positionAdd(data);
message('操作成功');
message.success('操作成功');
reloadTable();
};
```
@@ -218,10 +264,15 @@ BasicTable 内置右侧工具栏,支持:
const formParams = reactive({ name: '', status: '' });
const [register, {}] = useForm({
labelWidth: 80,
layout: 'horizontal',
colProps: { span: 6 } as ColProps,
submitOnReset: true,
rowProps: { gutter: [16, 0] },
colProps: {
xs: 24,
sm: 24,
md: 12,
lg: 8,
xl: 6,
},
labelCol: { span: 6, offset: 0 },
schemas, // querySchemas.ts 中定义
});
@@ -260,9 +311,9 @@ const loadDataTable = async (res: any) => {
| `setLoading(loading)` | 设置 loading |
:::tip 温馨提示
BasicTable 内部自动处理分页参数(pageNo/pageSize),调用方只需提供请求函数。操作列的权限控制通过 `TableAction` 的 `auth` 属性实现,与后端 `@permission_required` 对应。`render` 函数使用 Vue 的 `h()` 函数创建虚拟 DOM。
BasicTable 内部自动处理分页参数(pageNo/pageSize),调用方只需提供请求函数。操作列通过 `bodyCell` 插槽 + `v-perm` 指令实现权限控制,与后端 `@permission_required` 对应。`customRender` 函数使用 Vue 的 `h()` 函数创建虚拟 DOM。
:::
## 总结
BasicTable 封装了列定义(含 `render` 函数自定义渲染)、数据请求(自动分页和 loading)、操作列(`TableAction` + 权限控制)、多选、全屏、密度、列设置等表格常用能力。通过 `columns` 配置化定义列,`request` 函数自动管理数据加载,`actionColumn` 配置操作按钮。
BasicTable 封装了列定义(含 `customRender` 函数自定义渲染)、数据请求(自动分页和 loading)、操作列(`bodyCell` 插槽 + 权限控制)、多选、全屏、密度、列设置等表格常用能力。通过 `columns` 配置化定义列,`request` 函数自动管理数据加载,`bodyCell` 插槽配置操作按钮。
@@ -23,18 +23,21 @@ export function getNormalPath(path: string) {
return newPath[newPath.length - 1] === '/' ? newPath.slice(0, -1) : newPath;
}
// 确认弹窗封装
export function confirm(msg: string, type: 'warning') {
return ElMessageBox.confirm(msg, '温馨提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: type,
// 确认弹窗封装(使用 Ant Design Vue 的 Modal.confirm)
export function confirm(msg: string) {
return new Promise((resolve, reject) => {
Modal.confirm({
title: '温馨提示',
content: msg,
onOk: resolve,
onCancel: reject,
});
});
}
// 消息提示封装
export function message(msg: string, type = 'success') {
ElMessage[type](msg);
// 消息提示封装(使用 Ant Design Vue 的 message)
export function showMsg(msg: string, type = 'success') {
message[type](msg);
}
// 文件流下载
@@ -235,9 +238,9 @@ export enum PageEnum {
```
:::tip 温馨提示
`Storage` 工具类自动将键名转为大写(如 `access-token` → `ACCESS-TOKEN`),存储时包含过期时间,读取时自动检查是否过期。`auth.ts` 中的 `confirm` 和 `message` 函数是对 ElementPlus 的简封装,在业务组件中直接调用即可。
`Storage` 工具类自动将键名转为大写(如 `access-token` → `ACCESS-TOKEN`),存储时包含过期时间,读取时自动检查是否过期。`auth.ts` 中的 `confirm` 和 `message` 函数是对 Ant Design Vue 的简封装,在业务组件中直接调用即可。
:::
## 总结
工具函数库提供了 Storage(本地存储,支持过期)、auth(认证管理、树结构操作、文件下载)、dateUtil(日期格式化)、httpEnum/pageEnum(枚举定义)等通用能力。`confirm` 和 `message` 是 ElementPlus 的简封装,`arrayToTree`/`treeToArray` 处理菜单数据转换。
工具函数库提供了 Storage(本地存储,支持过期)、auth(认证管理、树结构操作、文件下载)、dateUtil(日期格式化)、httpEnum/pageEnum(枚举定义)等通用能力。`confirm` 和 `message` 是 Ant Design Vue 的简封装,`arrayToTree`/`treeToArray` 处理菜单数据转换。
@@ -26,9 +26,9 @@ src/views/
| 文件 | 职责 | 说明 |
|------|------|------|
| `index.vue` | 列表页 | 搜索表单 + 工具栏 + BasicTable + 编辑弹窗引用 |
| `edit.vue` | 编辑弹窗 | el-dialog + el-form,懒加载 |
| `detail.vue` | 详情弹窗 | el-dialog 展示详情,懒加载 |
| `columns.ts` | 表格列定义 | 定义列 prop、label、render 函数等 |
| `edit.vue` | 编辑弹窗 | a-modal + a-form,懒加载 |
| `detail.vue` | 详情弹窗 | a-modal 展示详情,懒加载 |
| `columns.ts` | 表格列定义 | 定列 dataIndex、title、customRender 函数等 |
| `querySchemas.ts` | 搜索表单定义 | FormSchema 数组,定义搜索字段 |
## index.vue 列表页
@@ -39,31 +39,52 @@ src/views/
<template>
<PageWrapper>
<!-- 搜索表单卡片 -->
<el-card :bordered="false" class="pt-3 mb-3 proCard">
<a-card :bordered="false" class="pt-3 mb-3 proCard">
<BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
</el-card>
</a-card>
<!-- 数据表格卡片 -->
<el-card :bordered="false" class="proCard">
<a-card :bordered="false" class="proCard">
<BasicTable
:columns="columns"
:request="loadDataTable"
:row-key="(row) => row.id"
ref="tableRef"
:actionColumn="actionColumn"
@selection-change="onSelectionChange"
:row-selection="{ onChange: onSelectionChange }"
scroll-x="1200"
>
<template #tableTitle>
<el-button type="primary" @click="handleAdd" v-perm="['sys:example:add']">
添加案例
</el-button>
<el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length"
v-perm="['sys:example:batchDelete']">
批量删除
</el-button>
<a-space>
<a-button type="primary" @click="handleAdd" v-perm="['sys:example:add']">
<template #icon><PlusOutlined /></template>
添加案例
</a-button>
<a-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:example:batchDelete']">
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
</a-space>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<a-space>
<a-button type="primary" @click="handleEdit(record)" v-perm="['sys:example:update']">
<template #icon><EditOutlined /></template>
编辑
</a-button>
<a-button type="primary" @click="handleDetail(record)" v-perm="['sys:example:detail']">
<template #icon><EyeOutlined /></template>
详情
</a-button>
<a-button type="primary" danger @click="handleDelete(record)" v-perm="['sys:example:delete']">
<template #icon><DeleteOutlined /></template>
删除
</a-button>
</a-space>
</template>
</template>
</BasicTable>
</el-card>
</a-card>
<!-- 编辑对话框组件 -->
<editDialog v-if="editVisible" :id="currentId" v-model:visible="editVisible" @success="reloadTable('noRefresh')" />
@@ -73,13 +94,13 @@ src/views/
</template>
<script lang="ts" setup>
import { reactive, ref, h, nextTick, defineAsyncComponent } from 'vue';
import { reactive, ref, nextTick, defineAsyncComponent } from 'vue';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons-vue';
import { schemas } from './querySchemas';
import { useForm } from '@/components/Form/index';
import { TableAction } from '@/components/Table';
import { getExamplePage, exampleDelete, exampleBatchDelete } from '@/api/tool/example';
import { columns } from './columns';
import { message, confirm } from '@/utils/auth';
import { message, Modal } from 'ant-design-vue';
const editDialog = defineAsyncComponent(() => import('./edit.vue'));
const detailDialog = defineAsyncComponent(() => import('./detail.vue'));
@@ -92,23 +113,6 @@ src/views/
const formParams = reactive({ name: '', type: '', status: '' });
const actionColumn = reactive({
width: 300,
label: '操作',
prop: 'action',
fixed: 'right',
render(record) {
return h(TableAction, {
style: 'button',
actions: [
{ label: '编辑', icon: 'Edit', type: 'warning', onClick: handleEdit.bind(null, record), auth: ['sys:example:update'] },
{ label: '详情', icon: 'View', type: '', onClick: handleDetail.bind(null, record), auth: ['sys:example:detail'] },
{ label: '删除', icon: 'Delete', type: 'danger', onClick: handleDelete.bind(null, record), auth: ['sys:example:delete'] },
],
});
},
});
const loadDataTable = async (params: any) => {
const result = await getExamplePage({ ...formParams, ...params });
return result;
@@ -119,14 +123,19 @@ src/views/
}
const [register, {}] = useForm({
labelWidth: 80,
layout: 'horizontal',
colProps: { span: 6 },
submitOnReset: true,
rowProps: { gutter: [16, 0] },
colProps: {
xs: 24,
sm: 24,
md: 12,
lg: 8,
xl: 6,
},
labelCol: { span: 6, offset: 0 },
schemas,
});
function handleSubmit(values) {
function handleSubmit(values: Recordable) {
handleReset();
for (const key in values) { formParams[key] = values[key]; }
reloadTable();
@@ -137,22 +146,27 @@ src/views/
}
const handleAdd = async () => { currentId.value = 0; await nextTick(); editVisible.value = true; };
const handleEdit = async (record) => { currentId.value = record.row.id; await nextTick(); editVisible.value = true; };
const handleDetail = async (record) => { currentId.value = record.row.id; await nextTick(); detailVisible.value = true; };
const handleEdit = async (record: Recordable) => { currentId.value = record.id; await nextTick(); editVisible.value = true; };
const handleDetail = async (record: Recordable) => { currentId.value = record.id; await nextTick(); detailVisible.value = true; };
async function handleDelete(record) {
async function handleDelete(record: Recordable) {
let ids = [];
if (!record) {
ids = selectionData.value.map(({ id }) => id);
if (!ids.length) { message('请选择要删除的数据', 'warning'); return; }
if (!ids.length) { message.warning('请选择要删除的数据'); return; }
}
await confirm('确定要删除选中的案例吗?');
record ? await exampleDelete(record.row.id) : await exampleBatchDelete(ids);
message('删除成功');
reloadTable();
Modal.confirm({
title: '提示',
content: '确定要删除选中的案例吗?',
onOk: async () => {
record ? await exampleDelete(record.id) : await exampleBatchDelete(ids);
message.success('删除成功');
reloadTable();
},
});
}
function onSelectionChange(value) { selectionData.value = value; }
function onSelectionChange(selectedRowKeys, selectedRows) { selectionData.value = selectedRows; }
</script>
```
@@ -160,37 +174,72 @@ src/views/
```typescript
import { h } from 'vue';
import { ElAvatar, ElTag } from 'element-plus';
import { Tag, Image } from 'ant-design-vue';
export const columns = [
{ type: 'selection' },
{ label: 'ID', prop: 'id', fixed: 'left', width: 50 },
{ label: '案例名称', prop: 'name', minWidth: 120 },
{
label: '案例图片', prop: 'avatar', minWidth: 120,
render(record) {
return h(ElAvatar, { size: 48, src: record.row.avatar, shape: 'square', fit: 'fill' });
title: 'ID',
dataIndex: 'id',
fixed: 'left',
width: 50,
},
{
title: '案例名称',
dataIndex: 'name',
width: 150,
},
{
title: '案例图片',
dataIndex: 'avatar',
width: 150,
customRender({ record }) {
return record.avatar
? h(Image, { src: record.avatar, width: 48, height: 48, fit: 'cover', preview: true })
: h('span', '-');
},
},
{
label: '案例类型', prop: 'type', minWidth: 100,
render(record) {
const statusMap = { 1: { text: '类型1', type: 'success' }, 2: { text: '类型2', type: 'danger' } };
const status = statusMap[record.row.type];
return h(ElTag, { type: status?.type || 'info' }, { default: () => status?.text || record.row.type });
title: '案例类型',
dataIndex: 'type',
width: 100,
customRender({ record }) {
const statusMap = { 1: { text: '类型1', color: 'success' }, 2: { text: '类型2', color: 'error' }, 3: { text: '类型3', color: 'warning' }, 4: { text: '类型4', color: 'default' } };
const status = statusMap[record.type];
return h(Tag, { color: status?.color || 'default' }, { default: () => status?.text || record.type });
},
},
{
label: '案例状态', prop: 'status', minWidth: 100,
render(record) {
const statusMap = { 1: { text: '正常', type: 'success' }, 2: { text: '禁用', type: 'danger' } };
const status = statusMap[record.row.status];
return h(ElTag, { type: status?.type || 'info' }, { default: () => status?.text || record.row.status });
title: '案例状态',
dataIndex: 'status',
width: 100,
customRender({ record }) {
const statusMap = { 1: { text: '正常', color: 'success' }, 2: { text: '禁用', color: 'error' } };
const status = statusMap[record.status];
return h(Tag, { color: status?.color || 'default' }, { default: () => status?.text || record.status });
},
},
{ label: '排序', prop: 'sort', minWidth: 100 },
{ label: '创建人', prop: 'createUser', minWidth: 100 },
{ label: '创建时间', prop: 'createTime', width: 180 },
{
title: '排序',
dataIndex: 'sort',
width: 100,
},
{
title: '创建人',
dataIndex: 'createUser',
width: 100,
},
{
title: '创建时间',
dataIndex: 'createTime',
width: 180,
},
{
title: '操作',
fixed: 'right',
dataIndex: 'action',
key: 'action',
width: 200,
},
];
```
@@ -201,23 +250,35 @@ import { FormSchema } from '@/components/Form/index';
export const schemas: FormSchema[] = [
{
field: 'name', component: 'Input', label: '案例名称',
componentProps: { placeholder: '请输入案例名称', clearable: true },
name: 'name',
component: 'Input',
label: '案例名称',
componentProps: { placeholder: '请输入案例名称', clearable: true, allowClear: true },
},
{
field: 'type', component: 'Select', label: '案例类型',
name: 'type',
component: 'Select',
label: '案例类型',
componentProps: {
placeholder: '请输入案例类型', clearable: true,
placeholder: '请输入案例类型',
clearable: true,
allowClear: true,
options: [
{ label: '类型1', value: 1 },
{ label: '类型2', value: 2 },
{ label: '类型3', value: 3 },
{ label: '类型4', value: 4 },
],
},
},
{
field: 'status', component: 'Select', label: '案例状态',
name: 'status',
component: 'Select',
label: '案例状态',
componentProps: {
placeholder: '请输入案例状态', clearable: true,
placeholder: '请输入案例状态',
clearable: true,
allowClear: true,
options: [
{ label: '正常', value: 1 },
{ label: '禁用', value: 2 },
@@ -234,13 +295,13 @@ export const schemas: FormSchema[] = [
用户搜索 → handleSubmit → 更新 formParams → reloadTable → 重新请求
用户新增 → handleAdd → currentId=0 → editVisible=true → edit.vue 加载 → 表单填写 → 提交
用户编辑 → handleEdit → currentId=id → editVisible=true → edit.vue 加载详情 → 修改 → 提交
用户删除 → confirm → API → reloadTable
用户删除 → Modal.confirm → API → reloadTable
```
:::tip 温馨提示
`columns.ts` 和 `querySchemas.ts` 独立为配置文件,便于维护和复用。`columns` 中的 `render` 函数使用 Vue 的 `h()` 创建虚拟 DOM,可实现任意复杂的自定义渲染。`querySchemas` 中的 `options` 硬编码或通过字典 API 动态获取。
`columns.ts` 和 `querySchemas.ts` 独立为配置文件,便于维护和复用。`columns` 中的 `customRender` 函数使用 Vue 的 `h()` 创建虚拟 DOM,可实现任意复杂的自定义渲染。`querySchemas` 中的 `options` 硬编码或通过字典 API 动态获取。
:::
## 总结
页面视图遵循 `index.vue` + `edit.vue` + `detail.vue` + `columns.ts` + `querySchemas.ts` 标准模式。列表页使用 `BasicForm` 搜索 + `BasicTable` 展示数据 + `TableAction` 操作按钮,编辑弹窗使用 `defineAsyncComponent` 懒加载 + `useLockFn` 防重复提交。
页面视图遵循 `index.vue` + `edit.vue` + `detail.vue` + `columns.ts` + `querySchemas.ts` 标准模式。列表页使用 `BasicForm` 搜索 + `BasicTable` 展示数据 + `bodyCell` 插槽操作按钮,编辑弹窗使用 `defineAsyncComponent` 懒加载 + `useLockFn` 防重复提交。