What is AutoForm
AutoForm is an automatic form generation system based on Zod Schema. Through declarative Schema definitions, it automatically generates a complete form interface including input controls, validation rules, and layout structure.
- Schema is the Form - A single Schema defines data structure, validation rules, and UI configuration simultaneously
- Type Safe - Full TypeScript type inference, from Schema to form data
- Zero Template Code - No need to write
v-foror repetitive form field templates
Basic Example
Create a simple user registration form:
<script lang="ts" setup>
import type { FormSubmitEvent } from '@nuxt/ui'
import type { z } from 'zod'
const { afz } = useAutoForm()
const toast = useToast()
const schema = afz.object({
username: afz.string('请填写用户名').min(3).max(20).regex(/^\w+$/),
email: afz.email({
controlProps: {
leadingIcon: 'i-lucide-mail',
placeholder: '请输入您的邮箱'
},
error: '请输入有效的邮箱地址'
}).meta({ hint: '邮箱' }),
password: afz.string({ controlProps: { type: 'password' } })
.min(8)
.regex(/[A-Z]/)
.regex(/[a-z]/)
.regex(/\d/),
confirmPassword: afz.string({ controlProps: { type: 'password' } }),
acceptTerms: afz.boolean({
controlProps: { label: '我同意服务条款和隐私政策', required: true }
})
}).refine(
data => data.password === data.confirmPassword,
{ message: '两次密码不一致', path: ['confirmPassword'] }
).refine(
data => data.acceptTerms === true,
{ message: '必须同意条款', path: ['acceptTerms'] }
)
type Schema = z.output<typeof schema>
const form = ref<Partial<Schema>>({})
async function onSubmit(event: FormSubmitEvent<Schema>) {
toast.add({
title: 'Success',
color: 'success',
description: JSON.stringify(event.data, null, 2)
})
}
</script>
<template>
<MAutoForm v-model="form" :schema="schema" @submit="onSubmit" />
</template>
API
Props
| Prop | Default | Type |
|---|---|---|
schema | SZod 对象 schema,定义表单字段 | |
state | N extends false ? FormState<S> : never表单状态对象,原地修改。 | |
loading | boolean 外部 loading 状态,与 | |
submit | true | boolean 是否显示默认提交按钮 |
submitButtonProps | ButtonProps提交按钮属性 | |
addButtonProps | ButtonProps数组字段添加按钮属性 | |
controls | AutoFormControls自定义控件映射 | |
globalMeta | ZodAutoFormFieldMeta全局字段元数据配置 | |
loadingAuto | true | boolean 是否启用自动 loading 功能。 |
validateOn | [] | FormInputEvents[]表单验证时机,详见 UForm 的 validateOn 属性 |
hiddenValue | 'keep' | "clear" | "keep"字段被 |
onSubmit | (): void | (event: FormSubmitEvent<FormData<S, T>>): void提交回调;返回 Promise 时配合 | |
id | string | number | |
validate | (state: Partial<InferInput<S>>): FormError<string>[] | Promise<FormError<string>[]>Custom validation function to validate the form state. | |
disabled | boolean Disable all inputs inside the form. | |
name | stringThe | |
validateOnInputDelay | `300` | numberDelay in milliseconds before validating the form on input events. |
transform | `true` | TIf true, applies schema transformations on submit. |
nested | `false` | NIf true, this form will attach to its parent Form and validate at the same time. |
acceptcharset | string | |
action | string | |
autocomplete | string | |
enctype | string | |
method | string | |
novalidate | false | true | "true" | "false" | |
target | string | |
modelValue | AutoFormStateType | |
ui | Record<string, c> & { root?: SlotClass; base?: SlotClass; collapsible?: SlotClass; header?: SlotClass; footer?: SlotClass; actions?: SlotClass; } |
Slots
| Slot | Type |
|---|---|
header | AutoFormSlotProps<AutoFormStateType> |
footer | AutoFormSlotProps<AutoFormStateType> |
submit | AutoFormSlotProps<AutoFormStateType> |
field-label | { label?: string | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
field-hint | { hint?: string | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
field-description | { description?: string | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
field-help | { help?: string | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
field-error | { error?: string | boolean | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
field-default | { error?: string | boolean | undefined; } & AutoFormFieldContext<AutoFormStateType, string> |
| Slot Pattern | Example | Description |
|---|---|---|
field-{slotType} | field-label, field-default | Generic slot, applies to all fields |
field-{slotType}:{fieldKey} | field-label:username, field-default:email | Specific field slot with full type inference |
field-{position}:{fieldKey} | field-before:profile, field-content:tasks | Nested field layout slot |
Emits
| Event | Type |
|---|---|
error | [FormErrorEvent](evt: "error", args_0: FormErrorEvent): void |
reset | [state: Partial<input<S>>](evt: "reset", state: Partial<input<S>>): void |
clear | [state: Partial<input<S>>](evt: "clear", state: Partial<input<S>>): void |
update:modelValue | [value: AutoFormStateType | undefined](event: "update:modelValue", value: AutoFormStateType | undefined): void |
Expose
You can access the typed component instance via useTemplateRef.
| Name | Type |
|---|---|
reset() | void Restore the baseline and apply schema defaults |
clear() | void Clear the form and keep schema defaults |
formRef | Ref<InstanceType<typeof UForm> | null> Template ref of the UForm component, provides access to all underlying form methods and properties |
formRef you can access all UForm underlying functionality, including submit(), validate(), clear(), getErrors(), setErrors() methods, and reactive properties such as errors, disabled, dirty, dirtyFields, touchedFields, blurredFields. See the Nuxt UI Form documentation for details.Theme
export default defineAppConfig({
ui: {
autoForm: {
slots: {
root: '',
base: 'space-y-4',
collapsible: 'space-y-4',
header: '',
footer: '',
actions: ''
}
}
}
})