16 KiB
16 KiB
前端页面视图
前端页面视图是用户直接交互的界面。项目使用 Vue3 + Ant Design Vue + Vite 构建。一个完整的 CRUD 页面由 5 个文件组成:
ui/src/views/tool/example/
├── index.vue # 主页面:搜索 + 表格 + 操作
├── edit.vue # 编辑弹窗:新增/编辑表单
├── detail.vue # 详情弹窗:查看记录详情
├── columns.ts # 表格列定义
└── querySchemas.ts # 搜索表单 Schema
1. 主页面 index.vue
主页面是模块的入口页面,包含搜索表单、数据表格和操作按钮。
核心结构
<template>
<PageWrapper>
<!-- 搜索表单卡片 -->
<a-card :bordered="false" class="pt-3 mb-3 proCard">
<BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
</a-card>
<!-- 数据表格卡片 -->
<a-card :bordered="false" class="proCard">
<BasicTable
:columns="columns"
:request="loadDataTable"
:row-key="(row) => row.id"
ref="tableRef"
:row-selection="{ onChange: onSelectionChange }"
scroll-x="1200"
>
<template #tableTitle>
<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>
</a-card>
<!-- 编辑对话框 -->
<editDialog v-if="editVisible" :id="currentId" v-model:visible="editVisible" @success="reloadTable('noRefresh')" />
<!-- 详情对话框 -->
<detailDialog v-if="detailVisible" :id="currentId" v-model:visible="detailVisible" @success="reloadTable('noRefresh')" />
</PageWrapper>
</template>
核心逻辑
<script lang="ts" setup>
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 { getExamplePage, exampleDelete, exampleBatchDelete } from '@/api/tool/example';
import { columns } from './columns';
import { message, Modal } from 'ant-design-vue';
// 动态导入弹窗组件
const editDialog = defineAsyncComponent(() => import('./edit.vue'));
const detailDialog = defineAsyncComponent(() => import('./detail.vue'));
// 响应式状态
const currentId = ref(0);
const editVisible = ref(false);
const detailVisible = ref(false);
const selectionData = ref([]);
const tableRef = ref();
// 查询参数
const formParams = reactive({ name: '', type: '', status: '' });
// 加载数据
const loadDataTable = async (params: any) => {
return await getExamplePage({ ...formParams, ...params });
};
// 注册搜索表单
const [register, {}] = useForm({
rowProps: { gutter: [16, 0] },
colProps: {
xs: 24,
sm: 24,
md: 12,
lg: 8,
xl: 6,
},
labelCol: { span: 6, offset: 0 },
schemas,
});
// 提交搜索
function handleSubmit(values: Recordable) {
handleReset();
for (const key in values) { formParams[key] = values[key]; }
reloadTable();
}
// 重置搜索
function handleReset() {
for (const key in formParams) { formParams[key] = ''; }
}
// 新增
const handleAdd = async () => { currentId.value = 0; await nextTick(); editVisible.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: Recordable) {
let ids = [];
if (!record) {
ids = selectionData.value.map(({ id }) => id);
if (!ids.length) { message.warning('请选择要删除的数据'); return; }
}
Modal.confirm({
title: '提示',
content: '确定要删除选中的案例吗?',
onOk: async () => {
record ? await exampleDelete(record.id) : await exampleBatchDelete(ids);
message.success('删除成功');
reloadTable();
},
});
}
</script>
关键点
- PageWrapper:页面容器,提供统一的页面布局
- BasicForm:搜索表单组件,通过
useForm注册 - BasicTable:数据表格组件,内置分页功能
- bodyCell 插槽:操作列通过
bodyCell插槽 +v-perm指令实现权限控制 - defineAsyncComponent:懒加载弹窗组件,优化首屏加载
- Modal.confirm:Ant Design Vue 的确认弹窗
- v-perm:权限指令,控制按钮显示
2. 编辑弹窗 edit.vue
编辑弹窗是独立组件,负责新增和编辑操作的表单展示与提交。
核心结构
<template>
<a-modal
v-model:visible="props.visible"
:title="props.id ? '编辑案例' : '新增案例'"
width="500px"
@cancel="dialogClose"
:mask-closable="false"
>
<a-form class="ls-form" ref="formRef" :model="formData" :label-col="{ style: { width: '80px' } }">
<a-form-item label="案例名称" name="name" :rules="{ required: true, message: '请输入案例名称', trigger: 'blur' }">
<a-input v-model:value="formData.name" placeholder="请输入案例名称" allow-clear />
</a-form-item>
<a-form-item label="案例图片" name="avatar">
<UploadImg v-model:image-url="formData.avatar" name="example" />
</a-form-item>
<a-form-item label="案例类型" name="type" :rules="{ required: true, message: '请选择案例类型', trigger: 'change' }">
<a-select v-model:value="formData.type" placeholder="请选择" allow-clear show-search :filter-option="filterOption">
<a-select-option v-for="item in optionsData.typeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="案例状态" name="status" :rules="{ required: true, message: '请选择状态', trigger: 'change' }">
<a-radio-group v-model:value="formData.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" :rules="{ required: true, message: '请输入排序', trigger: 'blur' }">
<a-input-number v-model:value="formData.sort" :min="0" :max="99999" />
</a-form-item>
</a-form>
<template #footer>
<span class="dialog-footer">
<a-button @click="dialogClose">取消</a-button>
<a-button :loading="subLoading" type="primary" @click="submit">确定</a-button>
</span>
</template>
</a-modal>
</template>
核心逻辑
<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import { getExampleDetail, exampleAdd, exampleUpdate } from '@/api/tool/example';
import { onMounted, reactive, shallowRef, watch } from 'vue';
import { message } from 'ant-design-vue';
import { useLockFn } from '@/utils/useLockFn';
const emit = defineEmits(['success', 'update:visible']);
const formRef = shallowRef<FormInstance>();
const formData = reactive({
id: '', name: '', avatar: '', type: 1, status: 1, sort: 0,
});
const props = defineProps({
visible: { type: Boolean, required: true, default: false },
id: { type: Number, required: true, default: 0 },
});
// 提交表单
const handleSubmit = async () => {
await formRef.value?.validate();
props.id ? await exampleUpdate(formData) : await exampleAdd(formData);
message.success('操作成功');
emit('update:visible', false);
emit('success');
};
// 关闭弹窗
const dialogClose = () => { emit('update:visible', false); };
// 防重复提交
const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);
// 编辑时加载数据
const setFormData = async () => {
const data = await getExampleDetail(props.id);
for (const key in formData) {
if (data[key] != null && data[key] != undefined) { formData[key] = data[key]; }
}
};
onMounted(() => {
if (props.id) { setFormData(); } else { resetForm(); }
});
watch(() => props.visible, (newVal) => {
if (newVal && props.id) { setFormData(); }
else if (newVal && !props.id) { resetForm(); }
});
</script>
关键点
- Props 接收:
visible控制弹窗显示,id区分新增/编辑模式 - 新增/编辑判断:
props.id ? exampleUpdate : exampleAdd - 防重复提交:
useLockFn包装提交函数,点击后按钮变为 loading 状态 - 数据回填:编辑模式下调用
getExampleDetail获取数据并填充表单 - 事件通信:
emit('update:visible')关闭弹窗,emit('success')通知刷新
3. 详情弹窗 detail.vue
详情弹窗用于展示记录的详细信息,使用 Ant Design Vue 的 a-descriptions 组件。
核心结构
<template>
<a-modal v-model:visible="props.visible" title="案例详情" width="750px" @cancel="dialogClose" :mask-closable="false">
<a-descriptions :column="2" bordered>
<a-descriptions-item label="案例名称">{{ formData.name || '-' }}</a-descriptions-item>
<a-descriptions-item label="案例图片">
<a-image v-if="formData.avatar" :src="formData.avatar" :width="80" :height="80" fit="cover" />
<span v-else>-</span>
</a-descriptions-item>
<a-descriptions-item label="案例类型">{{ getChoiceLabel('type', formData.type) }}</a-descriptions-item>
<a-descriptions-item label="案例状态">{{ getChoiceLabel('status', formData.status) }}</a-descriptions-item>
<a-descriptions-item label="排序">{{ formData.sort || '-' }}</a-descriptions-item>
</a-descriptions>
<template #footer>
<a-button @click="dialogClose">关闭</a-button>
</template>
</a-modal>
</template>
关键点
- a-descriptions:Ant Design Vue 的描述列表组件,用于展示详情
- getChoiceLabel:将枚举值转换为中文标签
- 图片预览:使用
a-image实现图片预览
4. 表格列定义 columns.ts
定义表格的列配置,包括列名、字段名、宽度和自定义渲染。
完整代码
import { h } from 'vue';
import { Tag, Image } from 'ant-design-vue';
export const columns = [
{
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', '-');
},
},
{
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 });
},
},
{
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 });
},
},
{
title: '排序',
dataIndex: 'sort',
width: 100,
},
{
title: '创建人',
dataIndex: 'createUser',
width: 100,
},
{
title: '创建时间',
dataIndex: 'createTime',
width: 180,
},
{
title: '操作',
fixed: 'right',
dataIndex: 'action',
key: 'action',
width: 200,
},
];
关键点
- title / dataIndex:Ant Design Vue 的列定义字段
- customRender 函数:使用 Vue 的
h()函数创建虚拟 DOM - Tag 组件:将状态值渲染为彩色标签(
color: 'success'/'error') - Image 组件:将图片 URL 渲染为缩略图
5. 搜索表单 querySchemas.ts
定义搜索表单的字段配置,使用项目封装的 FormSchema 类型。
完整代码
import { FormSchema } from '@/components/Form/index';
export const schemas: FormSchema[] = [
{
name: 'name',
component: 'Input',
label: '案例名称',
componentProps: { placeholder: '请输入案例名称', clearable: true, allowClear: true },
},
{
name: 'type',
component: 'Select',
label: '案例类型',
componentProps: {
placeholder: '请输入案例类型',
clearable: true,
allowClear: true,
options: [
{ label: '类型1', value: 1 },
{ label: '类型2', value: 2 },
{ label: '类型3', value: 3 },
{ label: '类型4', value: 4 },
],
},
},
{
name: 'status',
component: 'Select',
label: '案例状态',
componentProps: {
placeholder: '请输入案例状态',
clearable: true,
allowClear: true,
options: [
{ label: '正常', value: 1 },
{ label: '禁用', value: 2 },
],
},
},
];
关键点
- name:字段名,与后端查询参数对应
- component:表单组件类型:
Input/Select/DatePicker等 - componentProps:组件属性,透传给 Ant Design Vue 组件
- allowClear:Ant Design Vue 的清除属性
- options:Select 组件的下拉选项
文件关系图
index.vue(主页面)
├── import schemas from './querySchemas' ← 搜索表单配置
├── import columns from './columns' ← 表格列配置
├── import editDialog from './edit.vue' ← 编辑弹窗组件
├── import detailDialog from './detail.vue' ← 详情弹窗组件
└── import API from '@/api/tool/example' ← 接口请求
edit.vue(编辑弹窗)
└── import API from '@/api/tool/example' ← 接口请求
detail.vue(详情弹窗)
└── import API from '@/api/tool/example' ← 接口请求
开发要点
- 一个模块一个目录:放在
ui/src/views/{group}/{module}/下 - 5 个文件各司其职:主页面、编辑弹窗、详情弹窗、列定义、搜索 Schema
- 弹窗是独立组件:通过 Props 接收 ID,通过 Emit 通知父页面
- 列定义使用
h()渲染复杂内容:如状态标签、图片缩略图 - 搜索 Schema 使用
FormSchema类型:配置化定义表单字段 - 新增/编辑通过
id区分:0 为新增,非 0 为编辑 - 防重复提交使用
useLockFn:提交时按钮 loading - 操作列使用
bodyCell插槽:通过插槽自定义操作按钮 - 确认弹窗使用
Modal.confirm:Ant Design Vue 的确认弹窗 - 消息提示使用
message.success():Ant Design Vue 的消息提示
总结
前端页面统一使用 PageWrapper + BasicForm + BasicTable + bodyCell 插槽四件套,分页由 BasicTable 内置处理。每个模块包含 index.vue(列表页)、edit.vue(编辑弹窗)、detail.vue(详情弹窗)、columns.ts(列定义)、querySchemas.ts(搜索配置)五个文件。