【功能完善】INFRA:代码生成 vben5 antd 单表表单模版

This commit is contained in:
puhui999 2025-04-25 18:08:24 +08:00
parent ff39a2b57b
commit 03d3239463
2 changed files with 305 additions and 190 deletions

View File

@ -7,7 +7,10 @@ import { Tinymce as RichTextarea } from '#/components/tinymce';
import { ImageUpload, FileUpload } from "#/components/upload"; import { ImageUpload, FileUpload } from "#/components/upload";
import { message, Tabs, Form, Input, Textarea, Select, RadioGroup, Radio, CheckboxGroup, Checkbox, DatePicker } from 'ant-design-vue'; import { message, Tabs, Form, Input, Textarea, Select, RadioGroup, Radio, CheckboxGroup, Checkbox, DatePicker } from 'ant-design-vue';
import { DICT_TYPE, getDictOptions } from '#/utils/dict'; import { DICT_TYPE, getDictOptions } from '#/utils/dict';
#if($table.templateType == 2)## 树表需要导入这些
import { get${simpleClassName}List } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
import { handleTree } from '#/utils/tree';
#end
## 特殊:主子表专属逻辑 ## 特殊:主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 ) #if ( $table.templateType == 10 || $table.templateType == 12 )
#foreach ($subSimpleClassName in $subSimpleClassNames) #foreach ($subSimpleClassName in $subSimpleClassNames)
@ -44,29 +47,19 @@ const rules: Record<string, Rule[]> = {
#end #end
#end #end
}; };
#if (${table.templateType} == 2)## 树表特有父ID处理 ## 特殊:树表专属逻辑
const parentId = ref<number>(); // 新增下级时的父级 ID #if ( $table.templateType == 2 )
const ${classNameVar}Tree = ref<any[]>([]) // 树形结构
const getTitle = computed(() => { #end
if (formData.value?.id) {
return $t('ui.actionTitle.edit', ['${table.classComment}']);
}
return parentId.value
? $t('ui.actionTitle.create', ['下级${table.classComment}'])
: $t('ui.actionTitle.create', ['${table.classComment}']);
});
#else## 标准表标题
const getTitle = computed(() => { const getTitle = computed(() => {
return formData.value?.id return formData.value?.id
? $t('ui.actionTitle.edit', ['${table.classComment}']) ? $t('ui.actionTitle.edit', ['${table.classComment}'])
: $t('ui.actionTitle.create', ['${table.classComment}']); : $t('ui.actionTitle.create', ['${table.classComment}']);
}); });
#end
## 特殊:主子表专属逻辑 ## 特殊:主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 ) #if ( $table.templateType == 10 || $table.templateType == 12 )
#if ( $subTables && $subTables.size() > 0 ) #if ( $subTables && $subTables.size() > 0 )
/** 子表的表单 */ /** 子表的表单 */
const subTabsName = ref('$subClassNameVars.get(0)') const subTabsName = ref('$subClassNameVars.get(0)')
#foreach ($subClassNameVar in $subClassNameVars) #foreach ($subClassNameVar in $subClassNameVars)
@ -77,6 +70,34 @@ const getTitle = computed(() => {
#end #end
#end #end
/** 重置表单 */
const resetForm = () => {
formData.value = {
#foreach ($column in $columns)
#if ($column.createOperation || $column.updateOperation)
#if ($column.htmlType == "checkbox")
$column.javaField: [],
#else
$column.javaField: undefined,
#end
#end
#end
};
formRef.value?.resetFields();
}
## 特殊:树表专属逻辑
#if ( $table.templateType == 2 )
/** 获得${table.classComment}树 */
const get${simpleClassName}Tree = async () => {
${classNameVar}Tree.value = []
const data = await get${simpleClassName}List()
const root: Tree = { id: 0, name: '顶级${table.classComment}', children: [] }
root.children = handleTree(data, 'id', '${treeParentColumn.javaField}')
${classNameVar}Tree.value.push(root)
}
#end
const [Modal, modalApi] = useVbenModal({ const [Modal, modalApi] = useVbenModal({
async onConfirm() { async onConfirm() {
await formRef.value?.validate(); await formRef.value?.validate();
@ -101,7 +122,7 @@ const [Modal, modalApi] = useVbenModal({
#end #end
modalApi.lock(); modalApi.lock();
// 提交表单 // 提交表单
const data = formData.value; const data = formData.value as ${simpleClassName}Api.${simpleClassName};
## 特殊:主子表专属逻辑 ## 特殊:主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 ) #if ( $table.templateType == 10 || $table.templateType == 12 )
#if ( $subTables && $subTables.size() > 0 ) #if ( $subTables && $subTables.size() > 0 )
@ -132,18 +153,7 @@ const [Modal, modalApi] = useVbenModal({
}, },
async onOpenChange(isOpen: boolean) { async onOpenChange(isOpen: boolean) {
if (!isOpen) { if (!isOpen) {
formData.value = { resetForm()
#foreach ($column in $columns)
#if ($column.createOperation || $column.updateOperation)
#if ($column.htmlType == "checkbox")
$column.javaField: [],
#else
$column.javaField: undefined,
#end
#end
#end
};
formRef.value?.resetFields();
return; return;
} }
@ -160,8 +170,11 @@ const [Modal, modalApi] = useVbenModal({
modalApi.lock(false); modalApi.lock(false);
} }
} }
// 设置到 values
formData.value = data; formData.value = data;
#if ( $table.templateType == 2 )
// 加载树数据
await get${simpleClassName}Tree()
#end
}, },
}); });
</script> </script>
@ -180,7 +193,6 @@ const [Modal, modalApi] = useVbenModal({
#set ($dictType = $column.dictType) #set ($dictType = $column.dictType)
#set ($javaField = $column.javaField) #set ($javaField = $column.javaField)
#set ($javaType = $column.javaType) #set ($javaType = $column.javaType)
#set ($AttrName = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#set ($comment = $column.columnComment) #set ($comment = $column.columnComment)
#if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short") #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short")
#set ($dictMethod = "number") #set ($dictMethod = "number")
@ -224,14 +236,14 @@ const [Modal, modalApi] = useVbenModal({
<Form.Item label="${comment}" name="${javaField}"> <Form.Item label="${comment}" name="${javaField}">
<Select v-model:value="formData.${javaField}" placeholder="请选择${comment}"> <Select v-model:value="formData.${javaField}" placeholder="请选择${comment}">
#if ("" != $dictType)## 有数据字典 #if ("" != $dictType)## 有数据字典
<SelectOption <Select.Option
v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')" v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
:key="dict.value" :key="dict.value"
:label="dict.label" :label="dict.label"
:value="dict.value" :value="dict.value"
/> />
#else##没数据字典 #else##没数据字典
<SelectOption label="请选择字典生成" value="" /> <Select.Option label="请选择字典生成" value="" />
#end #end
</Select> </Select>
</Form.Item> </Form.Item>

View File

@ -1,11 +1,16 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}'; import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
import { Page, useVbenModal } from '@vben/common-ui'; import { Page, useVbenModal } from '@vben/common-ui';
import { Button, message,Tabs } from 'ant-design-vue'; import { formatDateTime } from '@vben/utils';
import { Download, Plus } from '@vben/icons'; import { Button, message,Tabs,Pagination,Form,RangePicker,DatePicker,Select,Input } from 'ant-design-vue';
import Form from './modules/form.vue'; import { DictTag } from '#/components/dict-tag';
import { DICT_TYPE, getDictOptions } from '#/utils/dict';
import ${simpleClassName}Form from './modules/form.vue';
import { Download, Plus, RefreshCw, Search } from '@vben/icons';
import { ContentWrap } from "#/components/content-wrap";
import { VxeColumn, VxeTable } from 'vxe-table';
import { getRangePickerDefaultProps } from '#/utils/date';
## 特殊:主子表专属逻辑 ## 特殊:主子表专属逻辑
#if ( $table.templateType == 11 || $table.templateType == 12 ) #if ( $table.templateType == 11 || $table.templateType == 12 )
@ -16,18 +21,16 @@ import Form from './modules/form.vue';
#end #end
#end #end
import { ref, h } from 'vue'; import { ref, h, reactive,onMounted } from 'vue';
import { $t } from '#/locales'; import { $t } from '#/locales';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
#if (${table.templateType} == 2)## 树表接口 #if (${table.templateType} == 2)## 树表接口
import { handleTree } from '@/utils/tree'
import { get${simpleClassName}List, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}'; import { get${simpleClassName}List, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#else## 标准表接口 #else## 标准表接口
import { get${simpleClassName}Page, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}'; import { get${simpleClassName}Page, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#end #end
import { downloadByData } from '#/utils/download'; import { downloadByData } from '#/utils/download';
import { useGridColumns, useGridFormSchema } from './data';
#if ($table.templateType == 12 || $table.templateType == 11) ## 内嵌和erp情况 #if ($table.templateType == 12 || $table.templateType == 11) ## 内嵌和erp情况
/** 子表的列表 */ /** 子表的列表 */
const subTabsName = ref('$subClassNameVars.get(0)') const subTabsName = ref('$subClassNameVars.get(0)')
@ -36,29 +39,67 @@ const select${simpleClassName} = ref<${simpleClassName}Api.${simpleClassName}>()
#end #end
#end #end
const loading = ref(true) // 列表的加载中
const list = ref<${simpleClassName}Api.${simpleClassName}[]>([]) // 列表的数据
## 特殊:树表专属逻辑(树不需要分页接口)
#if ( $table.templateType != 2 )
const total = ref(0) // 列表的总页数
#end
const queryParams = reactive({
## 特殊:树表专属逻辑(树不需要分页接口)
#if ( $table.templateType != 2 )
pageNo: 1,
pageSize: 10,
#end
#foreach ($column in $columns)
#if ($column.listOperation)
#if ($column.listOperationCondition != 'BETWEEN')
$column.javaField: undefined,
#end
#if ($column.htmlType == "datetime" || $column.listOperationCondition == "BETWEEN")
$column.javaField: undefined,
#end
#end
#end
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
/** 查询列表 */
const getList = async () => {
loading.value = true
try {
## 特殊:树表专属逻辑(树不需要分页接口)
#if ( $table.templateType == 2 )
const data = await get${simpleClassName}List(queryParams)
list.value = handleTree(data, 'id', '${treeParentColumn.javaField}')
#else
const data = await get${simpleClassName}Page(queryParams)
list.value = data.list
total.value = data.total
#end
} finally {
loading.value = false
}
}
/** 搜索按钮操作 */
const handleQuery = () => {
queryParams.pageNo = 1
getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
queryFormRef.value.resetFields()
handleQuery()
}
const [FormModal, formModalApi] = useVbenModal({ const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form, connectedComponent: ${simpleClassName}Form,
destroyOnClose: true, destroyOnClose: true,
}); });
#if (${table.templateType} == 2)## 树表特有:控制表格展开收缩
/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function toggleExpand() {
isExpanded.value = !isExpanded.value;
gridApi.grid.setAllTreeExpand(isExpanded.value);
}
#end
/** 刷新表格 */
function onRefresh() {
#if ($table.templateType == 12) ## 内嵌情况
gridApi.reload();
#else
gridApi.query();
#end
}
/** 创建${table.classComment} */ /** 创建${table.classComment} */
function onCreate() { function onCreate() {
formModalApi.setData({}).open(); formModalApi.setData({}).open();
@ -89,7 +130,7 @@ async function onDelete(row: ${simpleClassName}Api.${simpleClassName}) {
content: $t('ui.actionMessage.deleteSuccess', [row.id]), content: $t('ui.actionMessage.deleteSuccess', [row.id]),
key: 'action_process_msg', key: 'action_process_msg',
}); });
onRefresh(); await getList();
} catch { } catch {
hideLoading(); hideLoading();
} }
@ -97,147 +138,209 @@ async function onDelete(row: ${simpleClassName}Api.${simpleClassName}) {
/** 导出表格 */ /** 导出表格 */
async function onExport() { async function onExport() {
const data = await export${simpleClassName}(await gridApi.formApi.getValues()); try {
exportLoading.value = true;
const data = await export${simpleClassName}(queryParams);
downloadByData(data, '${table.classComment}.xls'); downloadByData(data, '${table.classComment}.xls');
}finally {
exportLoading.value = false;
}
} }
/** 表格操作按钮的回调函数 */ /** 初始化 **/
function onActionClick({ onMounted(() => {
code, getList()
row, })
}: OnActionClickParams<${simpleClassName}Api.${simpleClassName}>) {
switch (code) {
#if (${table.templateType} == 2)## 树表特有:新增下级
case 'append': {
onAppend(row);
break;
}
#end
case 'edit': {
onEdit(row);
break;
}
case 'delete': {
onDelete(row);
break;
}
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(onActionClick),
#if (${table.templateType} == 11)
height: '600px',
#else
height: 'auto',
#end
#if (${table.templateType} == 2)## 树表设置
treeConfig: {
parentField: '${treeParentColumn.javaField}',
rowField: 'id',
transform: true,
expandAll: true,
reserve: true,
},
pagerConfig: {
enabled: false,
},
#else## 标准表设置
pagerConfig: {
enabled: true,
},
#end
proxyConfig: {
ajax: {
#if (${table.templateType} == 2)## 树表数据加载
query: async (_, formValues) => {
return await get${simpleClassName}List(formValues);
},
#else## 标准表数据加载
query: async ({ page }, formValues) => {
return await get${simpleClassName}Page({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
#end
},
},
rowConfig: {
keyField: 'id',
isHover: true,
#if (${table.templateType} == 11)
isCurrent: true,
#end
},
toolbarConfig: {
refresh: { code: 'query' },
search: true,
},
} as VxeTableGridOptions<${simpleClassName}Api.${simpleClassName}>,
#if (${table.templateType} == 11)
gridEvents:{
cellClick: ({ row }: { row: ${simpleClassName}Api.${simpleClassName}}) => {
select${simpleClassName}.value = row;
},
}
#end
});
</script> </script>
<template> <template>
<Page auto-content-height> <Page auto-content-height>
<FormModal @success="onRefresh" /> <FormModal @success="getList" />
#if ($table.templateType == 11) ## erp情况 <ContentWrap>
<div> <!-- 搜索工作栏 -->
#end <Form
<Grid table-title="${table.classComment}列表"> class="-mb-15px"
#if ($table.templateType == 12) ## 内嵌情况 :model="queryParams"
<template #expand_content="{ row }"> ref="queryFormRef"
<!-- 子表的表单 --> layout="inline"
<Tabs v-model:active-key="subTabsName" class="mx-8"> >
#foreach ($subTable in $subTables) #foreach($column in $columns)
#set ($index = $foreach.count - 1) #if ($column.listOperation)
#set ($subClassNameVar = $subClassNameVars.get($index)) #set ($dictType = $column.dictType)
#set ($subSimpleClassName = $subSimpleClassNames.get($index)) #set ($javaField = $column.javaField)
#set ($subJoinColumn_strikeCase = $subJoinColumn_strikeCases.get($index)) #set ($javaType = $column.javaType)
<Tabs.TabPane key="$subClassNameVar" tab="${subTable.classComment}" force-render> #set ($comment = $column.columnComment)
<${subSimpleClassName}List :${subJoinColumn_strikeCase}="row?.id" /> #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short")
</Tabs.TabPane> #set ($dictMethod = "number")
#end #elseif ($javaType == "String")
</Tabs> #set ($dictMethod = "string")
#elseif ($javaType == "Boolean")
#set ($dictMethod = "boolean")
#end
#if ($column.htmlType == "input")
<Form.Item label="${comment}" name="${javaField}">
<Input
v-model:value="queryParams.${javaField}"
placeholder="请输入${comment}"
allowClear
@pressEnter="handleQuery"
class="!w-240px"
/>
</Form.Item>
#elseif ($column.htmlType == "select" || $column.htmlType == "radio" || $column.htmlType == "checkbox")
<Form.Item label="${comment}" name="${javaField}">
<Select
v-model:value="queryParams.${javaField}"
placeholder="请选择${comment}"
allowClear
class="!w-240px"
>
#if ("" != $dictType)## 设置了 dictType 数据字典的情况
<Select.Option
v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
#else## 未设置 dictType 数据字典的情况
<Select.Option label="请选择字典生成" value="" />
#end
</Select>
</Form.Item>
#elseif($column.htmlType == "datetime")
#if ($column.listOperationCondition != "BETWEEN")## 非范围
<Form.Item label="${comment}" name="${javaField}">
<DatePicker
v-model:value="queryParams.${javaField}"
valueFormat="YYYY-MM-DD"
placeholder="选择${comment}"
allowClear
class="!w-240px"
/>
</Form.Item>
#else## 范围
<Form.Item label="${comment}" name="${javaField}">
<RangePicker
v-model:value="queryParams.${javaField}"
v-bind="getRangePickerDefaultProps()"
class="!w-220px"
/>
</Form.Item>
#end
#end
#end
#end
<Form.Item>
<Button class="ml-2" @click="handleQuery" :icon="h(Search)">搜索</Button>
<Button class="ml-2" @click="resetQuery" :icon="h(RefreshCw)">重置</Button>
<Button
class="ml-2"
:icon="h(Plus)"
type="primary"
@click="onCreate"
v-access:code="['${permissionPrefix}:create']"
>
{{ $t('ui.actionTitle.create', ['示例联系人']) }}
</Button>
<Button
:icon="h(Download)"
type="primary"
class="ml-2"
:loading="exportLoading"
@click="onExport"
v-access:code="['${permissionPrefix}:export']"
>
{{ $t('ui.actionTitle.export') }}
</Button>
</Form.Item>
</Form>
</ContentWrap>
<!-- 列表 -->
<ContentWrap>
<vxe-table :data="list" show-overflow :loading="loading">
## 特殊:主子表专属逻辑
#if ( $table.templateType == 12 && $subTables && $subTables.size() > 0 )
<!-- 子表的列表 -->
<vxe-column type="expand" width="60">
<template #content="{ row }">
<!-- 子表的表单 -->
<Tabs v-model:active-key="subTabsName" class="mx-8">
#foreach ($subTable in $subTables)
#set ($index = $foreach.count - 1)
#set ($subClassNameVar = $subClassNameVars.get($index))
#set ($subSimpleClassName = $subSimpleClassNames.get($index))
#set ($subJoinColumn_strikeCase = $subJoinColumn_strikeCases.get($index))
<Tabs.TabPane key="$subClassNameVar" tab="${subTable.classComment}" force-render>
<${subSimpleClassName}List :${subJoinColumn_strikeCase}="row?.id" />
</Tabs.TabPane>
#end
</Tabs>
</template>
</vxe-column>
#end
#foreach($column in $columns)
#if ($column.listOperationResult)
#set ($dictType=$column.dictType)
#set ($javaField = $column.javaField)
#set ($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#set ($comment=$column.columnComment)
#if ($column.javaType == "LocalDateTime")## 时间类型
<vxe-column field="${javaField}" title="${comment}" align="center">
<template #default="{row}">
{{formatDateTime(row.${javaField})}}
</template>
</vxe-column>
#elseif($column.dictType && "" != $column.dictType)## 数据字典
<vxe-column field="${javaField}" title="${comment}" align="center">
<template #default="{row}">
<dict-tag :type="DICT_TYPE.$dictType.toUpperCase()" :value="row.${javaField}" />
</template>
</vxe-column>
#else
<vxe-column field="${javaField}" title="${comment}" align="center" />
#end
#end
#end
<vxe-column field="operation" title="操作" align="center">
<template #default="{row}">
<Button
size="small"
type="link"
@click="onEdit(row as any)"
v-access:code="['${permissionPrefix}:update']"
>
{{ $t('ui.actionTitle.edit') }}
</Button>
<Button
size="small"
type="link"
class="ml-2"
@click="onDelete(row as any)"
v-access:code="['${permissionPrefix}:delete']"
>
{{ $t('ui.actionTitle.delete') }}
</Button>
</template> </template>
#end </vxe-column>
<template #toolbar-tools> </vxe-table>
#if (${table.templateType} == 2)## 树表特有:展开/收缩按钮 <!-- 分页 -->
<Button @click="toggleExpand" class="mr-2"> <div class="mt-2 flex justify-end">
{{ isExpanded ? '收缩' : '展开' }} <Pagination
</Button> :total="total"
#end v-model:current="queryParams.pageNo"
<Button :icon="h(Plus)" type="primary" @click="onCreate" v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:create']"> v-model:page-size="queryParams.pageSize"
{{ $t('ui.actionTitle.create', ['${table.classComment}']) }} show-size-changer
</Button> @change="getList"
<Button />
:icon="h(Download)" </div>
type="primary" </ContentWrap>
class="ml-2"
@click="onExport"
v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:export']"
>
{{ $t('ui.actionTitle.export') }}
</Button>
</template>
</Grid>
#if ($table.templateType == 11) ## erp情况 #if ($table.templateType == 11) ## erp情况
<ContentWrap>
<!-- 子表的表单 --> <!-- 子表的表单 -->
<Tabs v-model:active-key="subTabsName" class="mt-2"> <Tabs v-model:active-key="subTabsName">
#foreach ($subTable in $subTables) #foreach ($subTable in $subTables)
#set ($index = $foreach.count - 1) #set ($index = $foreach.count - 1)
#set ($subClassNameVar = $subClassNameVars.get($index)) #set ($subClassNameVar = $subClassNameVars.get($index))
@ -248,7 +351,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
</Tabs.TabPane> </Tabs.TabPane>
#end #end
</Tabs> </Tabs>
</div> </ContentWrap>
#end #end
</Page> </Page>
</template> </template>