初始化项目

This commit is contained in:
ah--desktop
2025-09-10 00:33:25 +08:00
commit a305dcdc3f
1406 changed files with 114976 additions and 0 deletions
@@ -0,0 +1,274 @@
<script lang="ts" setup>
import type { RefSelectProps } from 'ant-design-vue/es/select';
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Card, message, Space } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
const isReverseActionButtons = ref(false);
const [BaseForm, formApi] = useVbenForm({
// 翻转操作按钮的位置
actionButtonsReverse: isReverseActionButtons.value,
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
// 使用 tailwindcss grid布局
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
layout: 'horizontal',
// 水平布局,label和input在同一行
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入用户名',
},
// 字段名
fieldName: 'field1',
// 界面显示的label
label: 'field1',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'field2',
label: 'field2',
},
{
component: 'Select',
componentProps: {
allowClear: true,
filterOption: true,
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
placeholder: '请选择',
showSearch: true,
},
fieldName: 'fieldOptions',
label: '下拉选',
},
],
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
function onSubmit(values: Record<string, any>) {
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
function handleClick(
action:
| 'batchAddSchema'
| 'batchDeleteSchema'
| 'componentRef'
| 'disabled'
| 'hiddenAction'
| 'hiddenResetButton'
| 'hiddenSubmitButton'
| 'labelWidth'
| 'resetDisabled'
| 'resetLabelWidth'
| 'reverseActionButtons'
| 'showAction'
| 'showResetButton'
| 'showSubmitButton'
| 'updateActionAlign'
| 'updateResetButton'
| 'updateSchema'
| 'updateSubmitButton',
) {
switch (action) {
case 'batchAddSchema': {
formApi.setState((prev) => {
const currentSchema = prev?.schema ?? [];
const newSchema = [];
for (let i = 0; i < 3; i++) {
newSchema.push({
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: `field${i}${Date.now()}`,
label: `field+`,
});
}
return {
schema: [...currentSchema, ...newSchema],
};
});
break;
}
case 'batchDeleteSchema': {
formApi.setState((prev) => {
const currentSchema = prev?.schema ?? [];
return {
schema: currentSchema.slice(0, -3),
};
});
break;
}
case 'componentRef': {
// 获取下拉组件的实例,并调用它的focus方法
formApi.getFieldComponentRef<RefSelectProps>('fieldOptions')?.focus?.();
break;
}
case 'disabled': {
formApi.setState({ commonConfig: { disabled: true } });
break;
}
case 'hiddenAction': {
formApi.setState({ showDefaultActions: false });
break;
}
case 'hiddenResetButton': {
formApi.setState({ resetButtonOptions: { show: false } });
break;
}
case 'hiddenSubmitButton': {
formApi.setState({ submitButtonOptions: { show: false } });
break;
}
case 'labelWidth': {
formApi.setState({
commonConfig: {
labelWidth: 150,
},
});
break;
}
case 'resetDisabled': {
formApi.setState({ commonConfig: { disabled: false } });
break;
}
case 'resetLabelWidth': {
formApi.setState({
commonConfig: {
labelWidth: 100,
},
});
break;
}
case 'reverseActionButtons': {
isReverseActionButtons.value = !isReverseActionButtons.value;
formApi.setState({ actionButtonsReverse: isReverseActionButtons.value });
break;
}
case 'showAction': {
formApi.setState({ showDefaultActions: true });
break;
}
case 'showResetButton': {
formApi.setState({ resetButtonOptions: { show: true } });
break;
}
case 'showSubmitButton': {
formApi.setState({ submitButtonOptions: { show: true } });
break;
}
case 'updateActionAlign': {
formApi.setState({
// 可以自行调整class
actionWrapperClass: 'text-center',
});
break;
}
case 'updateResetButton': {
formApi.setState({
resetButtonOptions: { disabled: true },
});
break;
}
case 'updateSchema': {
formApi.updateSchema([
{
componentProps: {
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
{
label: '选项3',
value: '3',
},
],
},
fieldName: 'fieldOptions',
},
]);
message.success('字段 `fieldOptions` 下拉选项更新成功。');
break;
}
case 'updateSubmitButton': {
formApi.setState({
submitButtonOptions: { loading: true },
});
break;
}
}
}
</script>
<template>
<Page description="表单组件api操作示例。" title="表单组件">
<Space class="mb-5 flex-wrap">
<Button @click="handleClick('updateSchema')">updateSchema</Button>
<Button @click="handleClick('labelWidth')">更改labelWidth</Button>
<Button @click="handleClick('resetLabelWidth')">还原labelWidth</Button>
<Button @click="handleClick('disabled')">禁用表单</Button>
<Button @click="handleClick('resetDisabled')">解除禁用</Button>
<Button @click="handleClick('reverseActionButtons')">
翻转操作按钮位置
</Button>
<Button @click="handleClick('hiddenAction')">隐藏操作按钮</Button>
<Button @click="handleClick('showAction')">显示操作按钮</Button>
<Button @click="handleClick('hiddenResetButton')">隐藏重置按钮</Button>
<Button @click="handleClick('showResetButton')">显示重置按钮</Button>
<Button @click="handleClick('hiddenSubmitButton')">隐藏提交按钮</Button>
<Button @click="handleClick('showSubmitButton')">显示提交按钮</Button>
<Button @click="handleClick('updateResetButton')">修改重置按钮</Button>
<Button @click="handleClick('updateSubmitButton')">修改提交按钮</Button>
<Button @click="handleClick('updateActionAlign')">
调整操作按钮位置
</Button>
<Button @click="handleClick('batchAddSchema')"> 批量添加表单项 </Button>
<Button @click="handleClick('batchDeleteSchema')">
批量删除表单项
</Button>
<Button @click="handleClick('componentRef')">下拉组件获取焦点</Button>
</Space>
<Card title="操作示例">
<BaseForm />
</Card>
</Page>
</template>
@@ -0,0 +1,447 @@
<script lang="ts" setup>
import type { UploadFile } from 'ant-design-vue';
import { h, ref, toRaw } from 'vue';
import { Page } from '@vben/common-ui';
import { useDebounceFn } from '@vueuse/core';
import { Button, Card, message, Spin, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useVbenForm, z } from '#/adapter/form';
import { getAllMenusApi } from '#/api';
import { upload_file } from '#/api/examples/upload';
import { $t } from '#/locales';
import DocButton from '../doc-button.vue';
const keyword = ref('');
const fetching = ref(false);
// 模拟远程获取数据
function fetchRemoteOptions({ keyword = '选项' }: Record<string, any>) {
fetching.value = true;
return new Promise((resolve) => {
setTimeout(() => {
const options = Array.from({ length: 10 }).map((_, index) => ({
label: `${keyword}-${index}`,
value: `${keyword}-${index}`,
}));
resolve(options);
fetching.value = false;
}, 1000);
});
}
const [BaseForm, baseFormApi] = useVbenForm({
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 在label后显示一个冒号
colon: true,
// 所有表单项
componentProps: {
class: 'w-full',
},
},
fieldMappingTime: [['rangePicker', ['startTime', 'endTime'], 'YYYY-MM-DD']],
// 提交函数
handleSubmit: onSubmit,
handleValuesChange(_values, fieldsChanged) {
message.info(`表单以下字段发生变化:${fieldsChanged.join(',')}`);
},
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'horizontal',
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入用户名',
},
// 字段名
fieldName: 'username',
// 界面显示的label
label: '字符串',
rules: 'required',
},
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'ApiSelect',
// 对应组件的参数
componentProps: {
// 菜单接口转options格式
afterFetch: (data: { name: string; path: string }[]) => {
return data.map((item: any) => ({
label: item.name,
value: item.path,
}));
},
// 菜单接口
api: getAllMenusApi,
autoSelect: 'first',
},
// 字段名
fieldName: 'api',
// 界面显示的label
label: 'ApiSelect',
},
{
component: 'ApiSelect',
// 对应组件的参数
componentProps: () => {
return {
api: fetchRemoteOptions,
// 禁止本地过滤
filterOption: false,
// 如果正在获取数据,使用插槽显示一个loading
notFoundContent: fetching.value ? undefined : null,
// 搜索词变化时记录下来, 使用useDebounceFn防抖。
onSearch: useDebounceFn((value: string) => {
keyword.value = value;
}, 300),
// 远程搜索参数。当搜索词变化时,params也会更新
params: {
keyword: keyword.value || undefined,
},
showSearch: true,
};
},
// 字段名
fieldName: 'remoteSearch',
// 界面显示的label
label: '远程搜索',
renderComponentContent: () => {
return {
notFoundContent: fetching.value ? h(Spin) : undefined,
};
},
rules: 'selectRequired',
},
{
component: 'ApiTreeSelect',
// 对应组件的参数
componentProps: {
// 菜单接口
api: getAllMenusApi,
// 菜单接口转options格式
labelField: 'name',
valueField: 'path',
childrenField: 'children',
},
// 字段名
fieldName: 'apiTree',
// 界面显示的label
label: 'ApiTreeSelect',
},
{
component: 'InputPassword',
componentProps: {
placeholder: '请输入密码',
},
fieldName: 'password',
label: '密码',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入',
},
fieldName: 'number',
label: '数字(带后缀)',
suffix: () => '¥',
},
{
component: 'IconPicker',
fieldName: 'icon',
label: '图标',
},
{
colon: false,
component: 'Select',
componentProps: {
allowClear: true,
filterOption: true,
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
placeholder: '请选择',
showSearch: true,
},
fieldName: 'options',
label: () => h(Tag, { color: 'warning' }, () => '😎自定义:'),
},
{
component: 'RadioGroup',
componentProps: {
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
},
fieldName: 'radioGroup',
label: '单选组',
},
{
component: 'Radio',
fieldName: 'radio',
label: '',
renderComponentContent: () => {
return {
default: () => ['Radio'],
};
},
},
{
component: 'CheckboxGroup',
componentProps: {
name: 'cname',
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
},
fieldName: 'checkboxGroup',
label: '多选组',
},
{
component: 'Checkbox',
fieldName: 'checkbox',
label: '',
renderComponentContent: () => {
return {
default: () => ['我已阅读并同意'],
};
},
rules: z
.boolean()
.refine((v) => v, { message: '为什么不同意?勾上它!' }),
},
{
component: 'Mentions',
componentProps: {
options: [
{
label: 'afc163',
value: 'afc163',
},
{
label: 'zombieJ',
value: 'zombieJ',
},
],
placeholder: '请输入',
},
fieldName: 'mentions',
label: '提及',
},
{
component: 'Rate',
fieldName: 'rate',
label: '评分',
},
{
component: 'Switch',
componentProps: {
class: 'w-auto',
},
fieldName: 'switch',
help: () =>
['这是一个多行帮助信息', '第二行', '第三行'].map((v) => h('p', v)),
label: '开关',
},
{
component: 'DatePicker',
fieldName: 'datePicker',
label: '日期选择框',
},
{
component: 'RangePicker',
fieldName: 'rangePicker',
label: '范围选择器',
},
{
component: 'TimePicker',
fieldName: 'timePicker',
label: '时间选择框',
},
{
component: 'TreeSelect',
componentProps: {
allowClear: true,
placeholder: '请选择',
showSearch: true,
treeData: [
{
label: 'root 1',
value: 'root 1',
children: [
{
label: 'parent 1',
value: 'parent 1',
children: [
{
label: 'parent 1-0',
value: 'parent 1-0',
children: [
{
label: 'my leaf',
value: 'leaf1',
},
{
label: 'your leaf',
value: 'leaf2',
},
],
},
{
label: 'parent 1-1',
value: 'parent 1-1',
},
],
},
{
label: 'parent 2',
value: 'parent 2',
},
],
},
],
treeNodeFilterProp: 'label',
},
fieldName: 'treeSelect',
label: '树选择',
},
{
component: 'Upload',
componentProps: {
// 更多属性见:https://ant.design/components/upload-cn
accept: '.png,.jpg,.jpeg',
// 自动携带认证信息
customRequest: upload_file,
disabled: false,
maxCount: 1,
multiple: false,
showUploadList: true,
// 上传列表的内建样式,支持四种基本样式 text, picture, picture-card 和 picture-circle
listType: 'picture-card',
},
fieldName: 'files',
label: $t('examples.form.file'),
renderComponentContent: () => {
return {
default: () => $t('examples.form.upload-image'),
};
},
rules: 'required',
},
],
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
function onSubmit(values: Record<string, any>) {
const files = toRaw(values.files) as UploadFile[];
const doneFiles = files.filter((file) => file.status === 'done');
const failedFiles = files.filter((file) => file.status !== 'done');
const msg = [
...doneFiles.map((file) => file.response?.url || file.url),
...failedFiles.map((file) => file.name),
].join(', ');
if (failedFiles.length === 0) {
message.success({
content: `${$t('examples.form.upload-urls')}: ${msg}`,
});
} else {
message.error({
content: `${$t('examples.form.upload-error')}: ${msg}`,
});
return;
}
// 如果需要可提交前替换为需要的urls
values.files = doneFiles.map((file) => file.response?.url || file.url);
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
function handleSetFormValue() {
/**
* 设置表单值(多个)
*/
baseFormApi.setValues({
checkboxGroup: ['1'],
datePicker: dayjs('2022-01-01'),
files: [
{
name: 'example.png',
status: 'done',
uid: '-1',
url: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp',
},
],
mentions: '@afc163',
number: 3,
options: '1',
password: '2',
radioGroup: '1',
rangePicker: [dayjs('2022-01-01'), dayjs('2022-01-02')],
rate: 3,
switch: true,
timePicker: dayjs('2022-01-01 12:00:00'),
treeSelect: 'leaf1',
username: '1',
});
// 设置单个表单值
baseFormApi.setFieldValue('checkbox', true);
}
</script>
<template>
<Page
content-class="flex flex-col gap-4"
description="表单组件基础示例,请注意,该页面用到的参数代码会添加一些简单注释,方便理解,请仔细查看。"
title="表单组件"
>
<template #description>
<div class="text-muted-foreground">
<p>
表单组件基础示例,请注意,该页面用到的参数代码会添加一些简单注释,方便理解,请仔细查看。
</p>
</div>
</template>
<template #extra>
<DocButton class="mb-2" path="/components/common-ui/vben-form" />
</template>
<Card title="基础示例">
<template #extra>
<Button type="primary" @click="handleSetFormValue">设置表单值</Button>
</template>
<BaseForm />
</Card>
</Page>
</template>
@@ -0,0 +1,111 @@
<script lang="ts" setup>
import { h } from 'vue';
import { Page } from '@vben/common-ui';
import { Card } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import DocButton from '../doc-button.vue';
const [CustomLayoutForm] = useVbenForm({
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
layout: 'horizontal',
schema: [
{
component: 'Select',
fieldName: 'field1',
label: '字符串',
},
{
component: 'TreeSelect',
fieldName: 'field2',
label: '字符串',
},
{
component: 'Mentions',
fieldName: 'field3',
label: '字符串',
},
{
component: 'Input',
fieldName: 'field4',
label: '字符串',
},
{
component: 'InputNumber',
fieldName: 'field5',
// 从第三列开始 相当于中间空了一列
formItemClass: 'col-start-3',
label: '前面空了一列',
},
{
component: 'Divider',
fieldName: '_divider',
formItemClass: 'col-span-3',
hideLabel: true,
renderComponentContent: () => {
return {
default: () => h('div', '分割线'),
};
},
},
{
component: 'Textarea',
fieldName: 'field6',
// 占满三列空间 基线对齐
formItemClass: 'col-span-3 items-baseline',
label: '占满三列',
},
{
component: 'Input',
fieldName: 'field7',
// 占满2列空间 从第二列开始 相当于前面空了一列
formItemClass: 'col-span-2 col-start-2',
label: '占满2列',
},
{
component: 'Input',
fieldName: 'field8',
// 左右留空
formItemClass: 'col-start-2',
label: '左右留空',
},
{
component: 'InputPassword',
fieldName: 'field9',
formItemClass: 'col-start-1',
label: '字符串',
},
],
// 一共三列
wrapperClass: 'grid-cols-3',
});
</script>
<template>
<Page
content-class="flex flex-col gap-4"
description="使用tailwind自定义表单项的布局"
title="表单自定义布局"
>
<template #description>
<div class="text-muted-foreground">
<p>使用tailwind自定义表单项的布局,使用Divider分割表单。</p>
</div>
</template>
<template #extra>
<DocButton class="mb-2" path="/components/common-ui/vben-form" />
</template>
<Card title="使用tailwind自定义布局">
<CustomLayoutForm />
</Card>
</Page>
</template>
@@ -0,0 +1,100 @@
<script lang="ts" setup>
import { h, markRaw } from 'vue';
import { Page } from '@vben/common-ui';
import { Card, Input, message } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
import TwoFields from './modules/two-fields.vue';
const [Form] = useVbenForm({
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
labelClass: 'w-2/6',
},
fieldMappingTime: [['field4', ['phoneType', 'phoneNumber'], null]],
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'horizontal',
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
fieldName: 'field',
label: '自定义后缀',
suffix: () => h('span', { class: 'text-red-600' }, '元'),
},
{
component: 'Input',
fieldName: 'field1',
label: '自定义组件slot',
renderComponentContent: () => ({
prefix: () => 'prefix',
suffix: () => 'suffix',
}),
},
{
component: h(Input, { placeholder: '请输入Field2' }),
fieldName: 'field2',
label: '自定义组件',
modelPropName: 'value',
rules: 'required',
},
{
component: 'Input',
fieldName: 'field3',
label: '自定义组件(slot)',
rules: 'required',
},
{
component: markRaw(TwoFields),
defaultValue: [undefined, ''],
disabledOnChangeListener: false,
fieldName: 'field4',
formItemClass: 'col-span-1',
label: '组合字段',
rules: z
.array(z.string().optional())
.length(2, '请选择类型并输入手机号码')
.refine((v) => !!v[0], {
message: '请选择类型',
})
.refine((v) => !!v[1] && v[1] !== '', {
message: '       输入手机号码',
})
.refine((v) => v[1]?.match(/^1[3-9]\d{9}$/), {
// 使用全角空格占位,将错误提示文字挤到手机号码输入框的下面
message: '       号码格式不正确',
}),
},
],
// 中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2',
});
function onSubmit(values: Record<string, any>) {
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
</script>
<template>
<Page description="表单组件自定义示例" title="表单组件">
<Card title="基础示例">
<Form>
<template #field3="slotProps">
<Input placeholder="请输入" v-bind="slotProps" />
</template>
</Form>
</Card>
</Page>
</template>
@@ -0,0 +1,262 @@
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { Button, Card, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
const [Form, formApi] = useVbenForm({
// 提交函数
handleSubmit: onSubmit,
schema: [
{
component: 'Input',
defaultValue: 'hidden value',
dependencies: {
show: false,
// 随意一个字段改变时,都会触发
triggerFields: ['field1Switch'],
},
fieldName: 'hiddenField',
label: '隐藏字段',
},
{
component: 'Switch',
defaultValue: true,
fieldName: 'field1Switch',
help: '通过Dom控制销毁',
label: '显示字段1',
},
{
component: 'Switch',
defaultValue: true,
fieldName: 'field2Switch',
help: '通过css控制隐藏',
label: '显示字段2',
},
{
component: 'Switch',
fieldName: 'field3Switch',
label: '禁用字段3',
},
{
component: 'Switch',
fieldName: 'field4Switch',
label: '字段4必填',
},
{
component: 'Input',
dependencies: {
if(values) {
return !!values.field1Switch;
},
// 只有指定的字段改变时,才会触发
triggerFields: ['field1Switch'],
},
// 字段名
fieldName: 'field1',
// 界面显示的label
label: '字段1',
},
{
component: 'Input',
dependencies: {
show(values) {
return !!values.field2Switch;
},
triggerFields: ['field2Switch'],
},
fieldName: 'field2',
label: '字段2',
},
{
component: 'Input',
dependencies: {
disabled(values) {
return !!values.field3Switch;
},
triggerFields: ['field3Switch'],
},
fieldName: 'field3',
label: '字段3',
},
{
component: 'Input',
dependencies: {
required(values) {
return !!values.field4Switch;
},
triggerFields: ['field4Switch'],
},
fieldName: 'field4',
label: '字段4',
},
{
component: 'Input',
dependencies: {
rules(values) {
if (values.field1 === '123') {
return 'required';
}
return null;
},
triggerFields: ['field1'],
},
fieldName: 'field5',
help: '当字段1的值为`123`时,必填',
label: '动态rules',
},
{
component: 'Select',
componentProps: {
allowClear: true,
class: 'w-full',
filterOption: true,
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
placeholder: '请选择',
showSearch: true,
},
dependencies: {
componentProps(values) {
if (values.field2 === '123') {
return {
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
{
label: '选项3',
value: '3',
},
],
};
}
return {};
},
triggerFields: ['field2'],
},
fieldName: 'field6',
help: '当字段2的值为`123`时,更改下拉选项',
label: '动态配置',
},
{
component: 'Input',
fieldName: 'field7',
label: '字段7',
},
],
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-4',
});
const [SyncForm] = useVbenForm({
handleSubmit: onSubmit,
schema: [
{
component: 'Input',
// 字段名
fieldName: 'field1',
// 界面显示的label
label: '字段1',
},
{
component: 'Input',
componentProps: {
disabled: true,
},
dependencies: {
trigger(values, form) {
form.setFieldValue('field2', values.field1);
},
// 只有指定的字段改变时,才会触发
triggerFields: ['field1'],
},
// 字段名
fieldName: 'field2',
// 界面显示的label
label: '字段2',
},
],
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-4',
});
function onSubmit(values: Record<string, any>) {
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
function handleDelete() {
formApi.setState((prev) => {
return {
schema: prev.schema?.filter((item) => item.fieldName !== 'field7'),
};
});
}
function handleAdd() {
formApi.setState((prev) => {
return {
schema: [
...(prev?.schema ?? []),
{
component: 'Input',
fieldName: `field${Date.now()}`,
label: '字段+',
},
],
};
});
}
function handleUpdate() {
formApi.setState((prev) => {
return {
schema: prev.schema?.map((item) => {
if (item.fieldName === 'field3') {
return {
...item,
label: '字段3-修改',
};
}
return item;
}),
};
});
}
</script>
<template>
<Page
description="表单组件动态联动示例,包含了常用的场景。增删改,本质上是修改schema,你也可以通过 `setState` 动态修改schema。"
title="表单组件"
>
<Card title="表单动态联动示例">
<template #extra>
<Button class="mr-2" @click="handleUpdate">修改字段3</Button>
<Button class="mr-2" @click="handleDelete">删除字段7</Button>
<Button @click="handleAdd">添加字段</Button>
</template>
<Form />
</Card>
<Card class="mt-5" title="字段同步,字段1数据与字段2数据同步">
<SyncForm />
</Card>
</Page>
</template>
@@ -0,0 +1,116 @@
<script lang="ts" setup>
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Card, message, Step, Steps, Switch } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
const currentTab = ref(0);
function onFirstSubmit(values: Record<string, any>) {
message.success({
content: `form1 values: ${JSON.stringify(values)}`,
});
currentTab.value = 1;
}
function onSecondReset() {
currentTab.value = 0;
}
function onSecondSubmit(values: Record<string, any>) {
message.success({
content: `form2 values: ${JSON.stringify(values)}`,
});
}
const [FirstForm, firstFormApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
},
handleSubmit: onFirstSubmit,
layout: 'horizontal',
resetButtonOptions: {
show: false,
},
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'formFirst',
label: '表单1字段',
rules: 'required',
},
],
submitButtonOptions: {
content: '下一步',
},
wrapperClass: 'grid-cols-1 md:grid-cols-1 lg:grid-cols-1',
});
const [SecondForm, secondFormApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
},
handleReset: onSecondReset,
handleSubmit: onSecondSubmit,
layout: 'horizontal',
resetButtonOptions: {
content: '上一步',
},
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'formSecond',
label: '表单2字段',
rules: 'required',
},
],
wrapperClass: 'grid-cols-1 md:grid-cols-1 lg:grid-cols-1',
});
const needMerge = ref(true);
async function handleMergeSubmit() {
const values = await firstFormApi
.merge(secondFormApi)
.submitAllForm(needMerge.value);
message.success({
content: `merged form values: ${JSON.stringify(values)}`,
});
}
</script>
<template>
<Page
description="表单组件合并示例:在某些场景下,例如分步表单,需要合并多个表单并统一提交。默认情况下,使用 Object.assign 规则合并表单。如果需要特殊处理数据,可以传入 false。"
title="表单组件"
>
<Card title="基础示例">
<template #extra>
<Switch
v-model:checked="needMerge"
checked-children="开启字段合并"
class="mr-4"
un-checked-children="关闭字段合并"
/>
<Button type="primary" @click="handleMergeSubmit">合并提交</Button>
</template>
<div class="mx-auto max-w-lg">
<Steps :current="currentTab" class="steps">
<Step title="表单1" />
<Step title="表单2" />
</Steps>
<div class="p-20">
<FirstForm v-show="currentTab === 0" />
<SecondForm v-show="currentTab === 1" />
</div>
</div>
</Card>
</Page>
</template>
@@ -0,0 +1,42 @@
<script lang="ts" setup>
import { Input, Select } from 'ant-design-vue';
const emit = defineEmits(['blur', 'change']);
const modelValue = defineModel<[string, string]>({
default: () => [undefined, undefined],
});
function onChange() {
emit('change', modelValue.value);
}
</script>
<template>
<div class="flex w-full gap-1">
<Select
v-model:value="modelValue[0]"
class="w-[80px]"
placeholder="类型"
allow-clear
:class="{ 'valid-success': !!modelValue[0] }"
:options="[
{ label: '个人', value: 'personal' },
{ label: '工作', value: 'work' },
{ label: '私密', value: 'private' },
]"
@blur="emit('blur')"
@change="onChange"
/>
<Input
placeholder="请输入11位手机号码"
class="flex-1"
allow-clear
:class="{ 'valid-success': modelValue[1]?.match(/^1[3-9]\d{9}$/) }"
v-model:value="modelValue[1]"
:maxlength="11"
type="tel"
@blur="emit('blur')"
@change="onChange"
/>
</div>
</template>
@@ -0,0 +1,216 @@
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { Card, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
const [QueryForm] = useVbenForm({
// 默认展开
collapsed: false,
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'horizontal',
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入用户名',
},
// 字段名
fieldName: 'username',
// 界面显示的label
label: '字符串',
},
{
component: 'InputPassword',
componentProps: {
placeholder: '请输入密码',
},
fieldName: 'password',
label: '密码',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入',
},
fieldName: 'number',
label: '数字(带后缀)',
suffix: () => '¥',
},
{
component: 'Select',
componentProps: {
allowClear: true,
filterOption: true,
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
placeholder: '请选择',
showSearch: true,
},
fieldName: 'options',
label: '下拉选',
},
{
component: 'DatePicker',
fieldName: 'datePicker',
label: '日期选择框',
},
],
// 是否可展开
showCollapseButton: true,
submitButtonOptions: {
content: '查询',
},
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
const [QueryForm1] = useVbenForm({
// 默认展开
collapsed: true,
collapsedRows: 2,
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'horizontal',
schema: (() => {
const schema = [];
for (let index = 0; index < 14; index++) {
schema.push({
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 字段名
fieldName: `field${index}`,
// 界面显示的label
label: `字段${index}`,
});
}
return schema;
})(),
// 是否可展开
showCollapseButton: true,
submitButtonOptions: {
content: '查询',
},
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
const [QueryForm2] = useVbenForm({
// 操作按钮组 newLine: 在新行显示。rowEnd: 在行内显示,靠右对齐(默认)。inline: 使用grid默认样式
actionLayout: 'newLine',
actionPosition: 'left', // 操作按钮组在左侧显示
// 默认折叠
collapsed: true,
collapsedRows: 3,
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'vertical',
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入用户名',
},
// 字段名
fieldName: 'username',
// 界面显示的label
label: '字符串',
},
{
component: 'InputPassword',
componentProps: {
placeholder: '请输入密码',
},
fieldName: 'password',
label: '密码',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入',
},
fieldName: 'number',
label: '数字(带后缀)',
suffix: () => '¥',
},
{
component: 'DatePicker',
fieldName: 'datePicker',
label: '日期选择框',
},
],
// 是否可展开
showCollapseButton: true,
submitButtonOptions: {
content: '查询',
},
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
function onSubmit(values: Record<string, any>) {
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
</script>
<template>
<Page
description="查询表单,常用语和表格组合使用,可进行收缩展开。"
title="表单组件"
>
<Card class="mb-5" title="查询表单,默认展开">
<QueryForm />
</Card>
<Card class="mb-5" title="查询表单,默认展开,垂直布局">
<QueryForm2 />
</Card>
<Card title="查询表单,默认折叠,折叠时保留2行">
<QueryForm1 />
</Card>
</Page>
</template>
@@ -0,0 +1,245 @@
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { Button, Card, message } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
const [Form, formApi] = useVbenForm({
// 所有表单项共用,可单独在表单内覆盖
commonConfig: {
// 所有表单项
componentProps: {
class: 'w-full',
},
},
// 提交函数
handleSubmit: onSubmit,
// 垂直布局,label和input在不同行,值为vertical
// 水平布局,label和input在同一行
layout: 'horizontal',
schema: [
{
// 组件需要在 #/adapter.ts内注册,并加上类型
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入',
},
// 字段名
fieldName: 'field1',
// 界面显示的label
label: '字段1',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
defaultValue: '默认值',
fieldName: 'field2',
label: '默认值(必填)',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'field3',
label: '默认值(非必填)',
rules: z.string().default('默认值').optional(),
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'field31',
label: '自定义信息',
rules: z.string().min(1, { message: '最少输入1个字符' }),
},
{
component: 'Input',
// 对应组件的参数
componentProps: {
placeholder: '请输入',
},
// 字段名
fieldName: 'field4',
// 界面显示的label
label: '邮箱',
rules: z.string().email('请输入正确的邮箱'),
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入',
},
fieldName: 'number',
label: '数字',
rules: 'required',
},
{
component: 'Select',
componentProps: {
allowClear: true,
filterOption: true,
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
placeholder: '请选择',
showSearch: true,
},
defaultValue: undefined,
fieldName: 'options',
label: '下拉选',
rules: 'selectRequired',
},
{
component: 'RadioGroup',
componentProps: {
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
},
fieldName: 'radioGroup',
label: '单选组',
rules: 'selectRequired',
},
{
component: 'CheckboxGroup',
componentProps: {
name: 'cname',
options: [
{
label: '选项1',
value: '1',
},
{
label: '选项2',
value: '2',
},
],
},
fieldName: 'checkboxGroup',
label: '多选组',
rules: 'selectRequired',
},
{
component: 'Checkbox',
fieldName: 'checkbox',
label: '',
renderComponentContent: () => {
return {
default: () => ['我已阅读并同意'],
};
},
rules: z.boolean().refine((value) => value, {
message: '请勾选',
}),
},
{
component: 'DatePicker',
defaultValue: undefined,
fieldName: 'datePicker',
label: '日期选择框',
rules: 'selectRequired',
},
{
component: 'RangePicker',
defaultValue: undefined,
fieldName: 'rangePicker',
label: '区间选择框',
rules: 'selectRequired',
},
{
component: 'InputPassword',
componentProps: {
placeholder: '请输入',
},
fieldName: 'password',
label: '密码',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'input-blur',
formFieldProps: {
validateOnChange: false,
validateOnModelUpdate: false,
},
help: 'blur时才会触发校验',
label: 'blur触发',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入',
},
fieldName: 'input-async',
label: '异步校验',
rules: z
.string()
.min(3, '用户名至少需要3个字符')
.refine(
async (username) => {
// 假设这是一个异步函数,模拟检查用户名是否已存在
const checkUsernameExists = async (
username: string,
): Promise<boolean> => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return username === 'existingUser';
};
const exists = await checkUsernameExists(username);
return !exists;
},
{
message: '用户名已存在',
},
),
},
],
// 大屏一行显示3个,中屏一行显示2个,小屏一行显示1个
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
});
function onSubmit(values: Record<string, any>) {
message.success({
content: `form values: ${JSON.stringify(values)}`,
});
}
</script>
<template>
<Page description="表单校验示例" title="表单组件">
<Card title="基础组件校验示例">
<template #extra>
<Button @click="() => formApi.validate()">校验表单</Button>
<Button class="mx-2" @click="() => formApi.resetValidate()">
清空校验信息
</Button>
</template>
<Form />
</Card>
</Page>
</template>
@@ -0,0 +1,183 @@
<script lang="ts" setup>
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Card, Switch } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
defineOptions({
name: 'ScrollToErrorTest',
});
const scrollEnabled = ref(true);
const [Form, formApi] = useVbenForm({
scrollToFirstError: scrollEnabled.value,
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入用户名',
},
fieldName: 'username',
label: '用户名',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入邮箱',
},
fieldName: 'email',
label: '邮箱',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入手机号',
},
fieldName: 'phone',
label: '手机号',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入地址',
},
fieldName: 'address',
label: '地址',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入备注',
},
fieldName: 'remark',
label: '备注',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入公司名称',
},
fieldName: 'company',
label: '公司名称',
rules: 'required',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入职位',
},
fieldName: 'position',
label: '职位',
rules: 'required',
},
{
component: 'Select',
componentProps: {
options: [
{ label: '男', value: 'male' },
{ label: '女', value: 'female' },
],
placeholder: '请选择性别',
},
fieldName: 'gender',
label: '性别',
rules: 'selectRequired',
},
],
showDefaultActions: false,
});
// 测试 validateAndSubmitForm(验证并提交)
async function testValidateAndSubmit() {
await formApi.validateAndSubmitForm();
}
// 测试 validate(手动验证整个表单)
async function testValidate() {
await formApi.validate();
}
// 测试 validateField(验证单个字段)
async function testValidateField() {
await formApi.validateField('username');
}
// 切换滚动功能
function toggleScrollToError() {
formApi.setState({ scrollToFirstError: scrollEnabled.value });
}
// 填充部分数据测试
async function fillPartialData() {
await formApi.resetForm();
await formApi.setFieldValue('username', '测试用户');
await formApi.setFieldValue('email', 'test@example.com');
}
</script>
<template>
<Page
description="测试表单验证失败时自动滚动到错误字段的功能"
title="滚动到错误字段测试"
>
<Card title="功能测试">
<template #extra>
<div class="flex items-center gap-2">
<Switch
v-model:checked="scrollEnabled"
@change="toggleScrollToError"
/>
<span>启用滚动到错误字段</span>
</div>
</template>
<div class="space-y-4">
<div class="rounded bg-blue-50 p-4">
<h3 class="mb-2 font-medium">测试说明:</h3>
<ul class="list-inside list-disc space-y-1 text-sm">
<li>所有验证方法在验证失败时都会自动滚动到第一个错误字段</li>
<li>可以通过右上角的开关控制是否启用自动滚动功能</li>
</ul>
</div>
<div class="rounded border p-4">
<h4 class="mb-3 font-medium">验证方法测试:</h4>
<div class="flex flex-wrap gap-2">
<Button type="primary" @click="testValidateAndSubmit">
测试 validateAndSubmitForm()
</Button>
<Button @click="testValidate"> 测试 validate() </Button>
<Button @click="testValidateField"> 测试 validateField() </Button>
</div>
<div class="mt-2 text-xs text-gray-500">
<p>• validateAndSubmitForm(): 验证表单并提交</p>
<p>• validate(): 手动验证整个表单</p>
<p>• validateField(): 验证单个字段(这里测试用户名字段)</p>
</div>
</div>
<div class="rounded border p-4">
<h4 class="mb-3 font-medium">数据填充测试:</h4>
<div class="flex flex-wrap gap-2">
<Button @click="fillPartialData"> 填充部分数据 </Button>
<Button @click="() => formApi.resetForm()"> 清空表单 </Button>
</div>
<div class="mt-2 text-xs text-gray-500">
<p>• 填充部分数据后验证,会滚动到第一个错误字段</p>
</div>
</div>
<Form />
</div>
</Card>
</Page>
</template>