feat(generator): 添加antdv-next专用代码生成模板

添加针对antdv-next框架的代码生成模板,支持useVbenForm和原生antd表单两种表单生成方式
包含API层、视图层、数据模型等完整模板文件,新增更新指南文档说明迁移步骤
This commit is contained in:
dap
2026-02-28 11:06:42 +08:00
parent a272c54561
commit 4f9caec9d5
10 changed files with 1914 additions and 0 deletions

View File

@@ -0,0 +1,215 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
#if(${dicts} != '')
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
#end
export const querySchema: FormSchemaGetter = () => [
#foreach($column in $columns)
#if($column.query)
#if($column.dictType)
#set($dictType=$column.dictType)
#else
#set($dictType="")
#end
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.htmlType == "input")
#set($component="Input")
#elseif($column.htmlType == "textarea")
#set($component="Textarea")
#elseif($column.htmlType == "select")
#set($component="Select")
#elseif($column.htmlType == "radio")
#set($component="RadioGroup")
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
#set($component="DatePicker")
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($component="RangePicker")
#else
#set($component="Input")
#end
{
component: '${component}',
#if($component == "Select" || $component == "RadioGroup")
componentProps: {
#if($dictType != "")
// 可选从DictEnum中获取 DictEnum.${dictType.toUpperCase()} 便于维护
options: getDictOptions('$dictType'),
#end
#if($component == "RadioGroup")
buttonStyle: 'solid',
optionType: 'button',
#end
},
#elseif($component == "DatePicker" || $component == "RangePicker")
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
#end
fieldName: '${column.javaField}',
label: '${comment}',
},
#end
#end
];
// 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
// export const columns: () => VxeGridProps['columns'] = () => [
export const columns: VxeGridProps['columns'] = [
#if($tplCategory != 'tree')
{ type: 'checkbox', width: 60 },
#end
#foreach($column in $columns)
#if($column.list)
#if($column.dictType)
#set($dictType=$column.dictType)
#else
#set($dictType="")
#end
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
{
title: '${comment}',
field: '${column.javaField}',
#if( $foreach.count == 1 && $tplCategory == 'tree')
treeNode: true,
#end
#if($dictType != "")
slots: {
default: ({ row }) => {
// 可选从DictEnum中获取 DictEnum.${dictType.toUpperCase()} 便于维护
return renderDict(row.${column.javaField}, '$dictType');
},
},
#end
},
#end
#end
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
width: 180,
},
];
#if($formComponent == "useForm")
export const ${popupComponent}Schema: FormSchemaGetter = () => [
#foreach($column in $columns)
#if($column.edit)
#if($column.dictType)
#set($dictType=$column.dictType)
#else
#set($dictType="")
#end
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.htmlType == "input")
#set($component="Input")
#elseif($column.htmlType == "textarea")
#set($component="Textarea")
#elseif($column.htmlType == "select")
#set($component="Select")
#elseif($column.htmlType == "radio")
#set($component="RadioGroup")
#elseif($column.htmlType == "checkbox")
#set($component="Checkbox")
#elseif($column.htmlType == "imageUpload")
#set($component="ImageUpload")
#elseif($column.htmlType == "fileUpload")
#set($component="FileUpload")
#elseif($column.htmlType == "editor")
#set($component="RichTextarea")
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
#set($component="DatePicker")
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($component="RangePicker")
#else
#set($component="Input")
#end
#if($column.required && $column.pk == false)
#set($required='true')
#else
#set($required='false')
#end
{
label: '${comment}',
fieldName: '${column.javaField}',
#if("" != $treeParentCode && $column.javaField == $treeParentCode)
component: 'TreeSelect',
#else
component: '${component}',
#end
#if($component == "DatePicker" || $component == "RangePicker")
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
#elseif($component == "ImageUpload")
componentProps: {
// accept: 'image/*', // 可选拓展名或者mime类型 ,拼接
// maxCount: 1, // 最大上传文件数 默认为1 为1会绑定为string而非string[]类型
},
#elseif($component == "FileUpload")
/**
* 注意这里获取为数组 需要自行定义回显/提交
* 文件上传还在demo阶段 可能有重大改动!
*/
componentProps: {
// accept: 'application/pdf', // 可选拓展名或者mime类型 ,拼接
// maxCount: 1, // 最大上传文件数 默认为1 为1会绑定为string而非string[]类型
},
#elseif($component == "RichTextarea")
componentProps: {
// disabled: false, // 是否只读
// height: 400 // 高度 默认400
},
#elseif($component == "Select" || $component == "RadioGroup" || $component == "Checkbox")
componentProps: {
#if($dictType != "")
// 可选从DictEnum中获取 DictEnum.${dictType.toUpperCase()} 便于维护
options: getDictOptions('$dictType'),
#end
#if($component == "RadioGroup")
buttonStyle: 'solid',
optionType: 'button',
#end
},
#end
#if(${column.pk})
dependencies: {
show: () => false,
triggerFields: [''],
},
#end
#if($required == 'true' && $column.pk == false)
#if($component == "Select" || $component == "RadioGroup" || $component == "Checkbox")
rules: 'selectRequired',
#else
rules: 'required',
#end
#end
},
#end
#end
];
#end

View File

@@ -0,0 +1,173 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { Page, useVben${PopupComponent} } from '@vben/common-ui';
import { Popconfirm, Space } from 'antdv-next';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
${businessName}Export,
${businessName}List,
${businessName}Remove,
} from '#/api/${moduleName}/${businessName}';
import type { ${BusinessName}Form } from '#/api/${moduleName}/${businessName}/model';
import { useBlobExport } from '#/utils/file/export';
import ${businessName}${PopupComponent} from './${businessName}-${popupComponent}.vue';
import { columns, querySchema } from './data';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
// 不需要直接删除
// fieldMappingTime: [
// [
// 'createTime',
// ['params[beginTime]', 'params[endTime]'],
// ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
// ],
// ],
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
// 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
// columns: columns(),
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await ${businessName}List({
pageNum: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: '${pkColumn.javaField}',
},
// 表格全局唯一表示 保存列配置需要用到
id: '${moduleName}-${businessName}-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [${BusinessName}${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
connectedComponent: ${businessName}${PopupComponent},
});
function handleAdd() {
${popupComponent}Api.setData({});
${popupComponent}Api.open();
}
async function handleEdit(row: Required<${BusinessName}Form>) {
${popupComponent}Api.setData({ id: row.${pkColumn.javaField} });
${popupComponent}Api.open();
}
async function handleDelete(row: Required<${BusinessName}Form>) {
await ${businessName}Remove(row.${pkColumn.javaField});
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: Required<${BusinessName}Form>) => row.${pkColumn.javaField});
window.modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await ${businessName}Remove(ids);
await tableApi.query();
},
});
}
const { exportBlob, exportLoading, buildExportFileName } = useBlobExport(${businessName}Export);
async function handleExport() {
const formValues = await tableApi.formApi.getValues();
const fileName = buildExportFileName('${functionName}数据');
exportBlob({ data: formValues, fileName });
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="${functionName}列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['${permissionPrefix}:export']"
:loading="exportLoading"
:disabled="exportLoading"
@click="handleExport"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['${permissionPrefix}:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['${permissionPrefix}:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<action-button
v-access:code="['${permissionPrefix}:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</action-button>
<Popconfirm placement="left" title="确认删除?" @confirm="handleDelete(row)">
<action-button
danger
v-access:code="['${permissionPrefix}:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</action-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<${BusinessName}${PopupComponent} @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,147 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { nextTick } from 'vue';
import { Page, useVben${PopupComponent} } from '@vben/common-ui';
import { Popconfirm, Space } from 'antdv-next';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { ${businessName}List, ${businessName}Remove } from '#/api/${moduleName}/${businessName}';
import type { ${BusinessName}Form } from '#/api/${moduleName}/${businessName}/model';
import { columns, querySchema } from './data';
import ${businessName}${PopupComponent} from './${businessName}-${popupComponent}.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
// 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
// columns: columns(),
columns,
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues = {}) => {
const resp = await ${businessName}List({
...formValues,
});
return { rows: resp };
},
// 默认请求接口后展开全部 不需要可以删除这段
querySuccess: () => {
nextTick(() => {
expandAll();
});
},
},
},
rowConfig: {
keyField: '${pkColumn.javaField}',
},
/**
* 虚拟滚动开关 默认关闭
* 数据量小可以选择关闭
* 如果遇到样式问题(空白、错位 滚动等)可以选择关闭虚拟滚动
*/
scrollY: {
enabled: false,
gt: 0,
},
treeConfig: {
parentField: '${treeParentCode}',
rowField: '${treeCode}',
// 自动转换为tree 由vxe处理 无需手动转换
transform: true,
},
// 表格全局唯一表示 保存列配置需要用到
id: '${moduleName}-${businessName}-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [${BusinessName}${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
connectedComponent: ${businessName}${PopupComponent},
});
function handleAdd() {
${popupComponent}Api.setData({});
${popupComponent}Api.open();
}
async function handleEdit(row: Required<${BusinessName}Form>) {
${popupComponent}Api.setData({ id: row.${pkColumn.javaField} });
${popupComponent}Api.open();
}
async function handleDelete(row: Required<${BusinessName}Form>) {
await ${businessName}Remove(row.${pkColumn.javaField});
await tableApi.query();
}
function expandAll() {
tableApi.grid?.setAllTreeExpand(true);
}
function collapseAll() {
tableApi.grid?.setAllTreeExpand(false);
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="${functionName}列表">
<template #toolbar-tools>
<Space>
<a-button @click="collapseAll">
{{ $t('pages.common.collapse') }}
</a-button>
<a-button @click="expandAll">
{{ $t('pages.common.expand') }}
</a-button>
<a-button
type="primary"
v-access:code="['${permissionPrefix}:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<action-button
v-access:code="['${permissionPrefix}:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</action-button>
<Popconfirm placement="left" title="确认删除?" @confirm="handleDelete(row)">
<action-button
danger
v-access:code="['${permissionPrefix}:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</action-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<${BusinessName}${PopupComponent} @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,376 @@
#if($formComponent == "useForm")
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVben${PopupComponent} } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { ${businessName}Add, ${businessName}Info, ${businessName}Update } from '#/api/${moduleName}/${businessName}';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { ${popupComponent}Schema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
// 默认占满两列
formItemClass: 'col-span-2',
// 默认label宽度 px
labelWidth: 80,
// 通用配置项 会影响到所有表单项
componentProps: {
class: 'w-full',
},
},
schema: ${popupComponent}Schema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [Basic${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
// 在这里更改宽度
class: 'w-[550px]',
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
${popupComponent}Api.${popupComponent}Loading(true);
const { id } = ${popupComponent}Api.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await ${businessName}Info(id);
await formApi.setValues(record);
}
await markInitialized();
${popupComponent}Api.${popupComponent}Loading(false);
},
});
async function handleConfirm() {
try {
${popupComponent}Api.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? ${businessName}Update(data) : ${businessName}Add(data));
resetInitialized();
emit('reload');
${popupComponent}Api.close();
} catch (error) {
console.error(error);
} finally {
${popupComponent}Api.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<Basic${PopupComponent} :title="title">
<BasicForm />
</Basic${PopupComponent}>
</template>
#else
<!--
使用antdv-next原生Form生成 详细用法参考antdv-next Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { FormInstance } from 'antdv-next';
import type { Rule } from 'antdv-next/dist/form/types';
import { computed, ref } from 'vue';
import {
CheckboxGroup,
DatePicker,
Form,
FormItem,
Input,
RadioGroup,
Select,
Textarea,
} from 'antdv-next';
import { ImageUpload, FileUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';
#if(${dicts} != '')
import { getDictOptions } from '#/utils/dict';
#end
import { useVben${PopupComponent} } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { ${businessName}Add, ${businessName}Info, ${businessName}Update } from '#/api/${moduleName}/${businessName}';
import type { ${BusinessName}Form } from '#/api/${moduleName}/${businessName}/model';
import { useBeforeCloseDiff } from '#/utils/popup';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
/**
* 定义默认值 用于reset
*/
const defaultValues: Partial<${BusinessName}Form> = {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.htmlType == "checkbox")
$column.javaField: []#if($foreach.count != $columns.size()),#end
#else
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
#end
};
/**
* 表单数据ref
*/
const formData = ref(defaultValues);
type AntdFormRules<T> = Partial<Record<keyof T, Rule[]>> & {
[key: string]: Rule[];
};
/**
* 表单校验规则
*/
const formRules = ref<AntdFormRules<${BusinessName}Form>>({
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.required && $column.pk == false)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
$column.javaField: [
{ required: true, message: "$comment不能为空" },
]#if($foreach.count != $columns.size()),#end
#end
#end
#end
});
const formInstance = ref<FormInstance>();
function customFormValueGetter() {
return JSON.stringify(formData.value);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: customFormValueGetter,
currentGetter: customFormValueGetter,
},
);
const [Basic${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
class: 'w-[550px]',
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
${popupComponent}Api.${popupComponent}Loading(true);
const { id } = ${popupComponent}Api.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await ${businessName}Info(id);
// 只赋值存在的字段
const filterRecord = pick(record, Object.keys(defaultValues));
formData.value = filterRecord;
}
await markInitialized();
${popupComponent}Api.${popupComponent}Loading(false);
},
});
async function handleConfirm() {
try {
${popupComponent}Api.lock(true);
await formInstance.value?.validate();
// 可能会做数据处理 使用cloneDeep深拷贝
const data = cloneDeep(formData.value);
await (isUpdate.value ? ${businessName}Update(data) : ${businessName}Add(data));
resetInitialized();
emit('reload');
${popupComponent}Api.close();
} catch (error) {
console.error(error);
} finally {
${popupComponent}Api.lock(false);
}
}
async function handleClosed() {
formData.value = defaultValues;
formInstance.value?.resetFields();
resetInitialized();
}
</script>
<template>
<Basic${PopupComponent} :title="title">
<Form :label-col="{ span: 4 }" ref="formInstance" :model="formData">
#foreach($column in $columns)
#set($field=$column.javaField)
#if(($column.insert || $column.edit) && !$column.pk)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#set($dictType=$column.dictType)
#if($column.htmlType == "input")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Input v-model:value="formData.${field}" :placeholder="$t('ui.formRules.required')" />
</FormItem>
#elseif($column.htmlType == "imageUpload")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- props参考apps/web-antd/src/components/upload/src/props.d.ts -->
<!-- maxCount为1(默认)时只允许上传一个文件 会自动绑定为string而非string[] -->
<ImageUpload :max-count="1" v-model:value="formData.${field}" />
</FormItem>
#elseif($column.htmlType == "fileUpload")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- props参考apps/web-antd/src/components/upload/src/props.d.ts -->
<!-- maxCount为1(默认)时只允许上传一个文件 会自动绑定为string而非string[] -->
<FileUpload :max-count="1" v-model:value="formData.${field}" />
</FormItem>
#elseif($column.htmlType == "editor")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Tinymce
:disabled="false"
v-model="formData.${field}"
/>
</FormItem>
#elseif($column.htmlType == "select" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Select
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
:getPopupContainer="getPopupContainer"
:placeholder="$t('ui.formRules.selectRequired')"
/>
</FormItem>
#elseif($column.htmlType == "select" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Select
v-model:value="formData.${field}"
:options="[]"
:getPopupContainer="getPopupContainer"
:placeholder="$t('ui.formRules.selectRequired')"
/>
</FormItem>
#elseif($column.htmlType == "checkbox" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<CheckboxGroup
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
/>
</FormItem>
#elseif($column.htmlType == "checkbox" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<CheckboxGroup
v-model:value="formData.${field}"
:options="[]"
/>
</FormItem>
#elseif($column.htmlType == "radio" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<RadioGroup
option-type="button"
button-style="solid"
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
/>
</FormItem>
#elseif($column.htmlType == "radio" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<RadioGroup
option-type="button"
button-style="solid"
v-model:value="formData.${field}"
:options="[]"
/>
</FormItem>
#elseif($column.htmlType == "datetime")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- 需要自行调整参数 -->
<DatePicker
v-model:value="formData.${field}"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
/>
</FormItem>
#elseif($column.htmlType == "textarea")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Textarea
v-model:value="formData.${field}"
:placeholder="$t('ui.formRules.required')"
:rows="4"
/>
</FormItem>
#end
#end
#end
</Form>
</Basic${PopupComponent}>
</template>
#end

View File

@@ -0,0 +1,412 @@
#if($formComponent == "useForm")
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVben${PopupComponent} } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep, getPopupContainer, listToTree } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { ${businessName}Add, ${businessName}Info, ${businessName}List, ${businessName}Update } from '#/api/${moduleName}/${businessName}';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { ${popupComponent}Schema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
// 默认占满两列
formItemClass: 'col-span-2',
// 默认label宽度 px
labelWidth: 80,
// 通用配置项 会影响到所有表单项
componentProps: {
class: 'w-full',
},
},
schema: ${popupComponent}Schema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
async function setup${BusinessName}Select() {
const listData = await ${businessName}List();
const treeData = listToTree(listData, { id: '${treeCode}', pid: '${treeParentCode}' });
formApi.updateSchema([{
fieldName: '${treeParentCode}',
componentProps: {
treeData,
treeLine: { showLeafIcon: false },
fieldNames: { label: '${treeName}', value: '${treeCode}' },
treeDefaultExpandAll: true,
getPopupContainer,
},
}]);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [Basic${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
// 在这里更改宽度
class: 'w-[550px]',
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
${popupComponent}Api.${popupComponent}Loading(true);
const { id } = ${popupComponent}Api.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await ${businessName}Info(id);
await formApi.setValues(record);
}
await setup${BusinessName}Select();
await markInitialized();
${popupComponent}Api.${popupComponent}Loading(false);
},
});
async function handleConfirm() {
try {
${popupComponent}Api.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? ${businessName}Update(data) : ${businessName}Add(data));
resetInitialized();
emit('reload');
${popupComponent}Api.close();
} catch (error) {
console.error(error);
} finally {
${popupComponent}Api.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<Basic${PopupComponent} :title="title">
<BasicForm />
</Basic${PopupComponent}>
</template>
#else
<!--
使用antdv-next原生Form生成 详细用法参考antdv-next Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { FormInstance } from 'antdv-next';
import type { Rule } from 'antdv-next/dist/form/types';
import { computed, ref } from 'vue';
import {
CheckboxGroup,
DatePicker,
Form,
FormItem,
Input,
RadioGroup,
Select,
Textarea,
TreeSelect,
} from 'antdv-next';
import { ImageUpload, FileUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';
#if(${dicts} != '')
import { getDictOptions } from '#/utils/dict';
#end
import { useVben${PopupComponent} } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep, listToTree } from '@vben/utils';
import { ${businessName}Add, ${businessName}Info, ${businessName}List, ${businessName}Update } from '#/api/${moduleName}/${businessName}';
import type { ${BusinessName}Form } from '#/api/${moduleName}/${businessName}/model';
import { useBeforeCloseDiff } from '#/utils/popup';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
/**
* 定义默认值 用于reset
*/
const defaultValues: Partial<${BusinessName}Form> = {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.htmlType == "checkbox")
$column.javaField: []#if($foreach.count != $columns.size()),#end
#else
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
#end
};
/**
* 表单数据ref
*/
const formData = ref(defaultValues);
type AntdFormRules<T> = Partial<Record<keyof T, Rule[]>> & {
[key: string]: Rule[];
};
/**
* 表单校验规则
*/
const formRules = ref<AntdFormRules<${BusinessName}Form>>({
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.required && $column.pk == false)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
$column.javaField: [
{ required: true, message: "$comment不能为空" },
]#if($foreach.count != $columns.size()),#end
#end
#end
#end
});
const formInstance = ref<FormInstance>();
function customFormValueGetter() {
return JSON.stringify(formData.value);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: customFormValueGetter,
currentGetter: customFormValueGetter,
},
);
const treeData = ref<any[]>([]);
async function setup${BusinessName}Select() {
const listData = await ${businessName}List();
treeData.value = listToTree(listData, { id: '${treeCode}', pid: '${treeParentCode}' });
}
const [Basic${PopupComponent}, ${popupComponent}Api] = useVben${PopupComponent}({
class: 'w-[550px]',
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
${popupComponent}Api.${popupComponent}Loading(true);
const { id } = ${popupComponent}Api.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await ${businessName}Info(id);
// 只赋值存在的字段
const filterRecord = pick(record, Object.keys(defaultValues));
formData.value = filterRecord;
}
await setup${BusinessName}Select();
await markInitialized();
${popupComponent}Api.${popupComponent}Loading(false);
},
});
async function handleConfirm() {
try {
${popupComponent}Api.lock(true);
await formInstance.value?.validate();
// 可能会做数据处理 使用cloneDeep深拷贝
const data = cloneDeep(formData.value);
await (isUpdate.value ? ${businessName}Update(data) : ${businessName}Add(data));
resetInitialized();
emit('reload');
${popupComponent}Api.close();
} catch (error) {
console.error(error);
} finally {
${popupComponent}Api.lock(false);
}
}
async function handleClosed() {
formData.value = defaultValues;
formInstance.value?.resetFields();
resetInitialized();
}
</script>
<template>
<Basic${PopupComponent} :title="title">
<Form :label-col="{ span: 4 }" ref="formInstance" :model="formData">
#foreach($column in $columns)
#set($field=$column.javaField)
#if(($column.insert || $column.edit) && !$column.pk)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#set($dictType=$column.dictType)
#if("" != $treeParentCode && $column.javaField == $treeParentCode)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<TreeSelect
v-model:value="formData.${treeParentCode}"
:treeData="treeData"
:tree-line="{ showLeafIcon: false }"
:treeDefaultExpandAll="true"
:fieldNames="{ label: '${treeName}', value: '${treeCode}' }"
:placeholder="$t('ui.formRules.selectRequired')"
:getPopupContainer="getPopupContainer"
/>
</FormItem>
#elseif($column.htmlType == "input")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Input v-model:value="formData.${field}" :placeholder="$t('ui.formRules.required')" />
</FormItem>
#elseif($column.htmlType == "imageUpload")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- props参考apps/web-antd/src/components/upload/src/props.d.ts -->
<!-- maxCount为1(默认)时只允许上传一个文件 会自动绑定为string而非string[] -->
<ImageUpload :max-count="1" v-model:value="formData.${field}" />
</FormItem>
#elseif($column.htmlType == "fileUpload")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- props参考apps/web-antd/src/components/upload/src/props.d.ts -->
<!-- maxCount为1(默认)时只允许上传一个文件 会自动绑定为string而非string[] -->
<FileUpload :max-count="1" v-model:value="formData.${field}" />
</FormItem>
#elseif($column.htmlType == "editor")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Tinymce
:disabled="false"
v-model="formData.${field}"
/>
</FormItem>
#elseif($column.htmlType == "select" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Select
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
:getPopupContainer="getPopupContainer"
:placeholder="$t('ui.formRules.selectRequired')"
/>
</FormItem>
#elseif($column.htmlType == "select" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Select
v-model:value="formData.${field}"
:options="[]"
:getPopupContainer="getPopupContainer"
:placeholder="$t('ui.formRules.selectRequired')"
/>
</FormItem>
#elseif($column.htmlType == "checkbox" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<CheckboxGroup
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
/>
</FormItem>
#elseif($column.htmlType == "checkbox" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<CheckboxGroup
v-model:value="formData.${field}"
:options="[]"
/>
</FormItem>
#elseif($column.htmlType == "radio" && "" != $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<RadioGroup
option-type="button"
button-style="solid"
v-model:value="formData.${field}"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:options="getDictOptions('$dictType', true)"
#else
:options="getDictOptions('$dictType')"
#end
/>
</FormItem>
#elseif($column.htmlType == "radio" && "" == $dictType)
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<RadioGroup
option-type="button"
button-style="solid"
v-model:value="formData.${field}"
:options="[]"
/>
</FormItem>
#elseif($column.htmlType == "datetime")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<!-- 需要自行调整参数 -->
<DatePicker
v-model:value="formData.${field}"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
/>
</FormItem>
#elseif($column.htmlType == "textarea")
<FormItem label="${comment}" name="${field}" :rules="formRules.${field}">
<Textarea
v-model:value="formData.${field}"
:placeholder="$t('ui.formRules.required')"
:rows="4"
/>
</FormItem>
#end
#end
#end
</Form>
</Basic${PopupComponent}>
</template>
#end