快速开始

了解 AutoForm 的核心设计理念和基本使用方式。
查看源码

什么是 AutoForm

AutoForm 是一个基于 Zod Schema 的自动表单生成系统。通过声明式的 Schema 定义,自动生成完整的表单界面,包括输入控件、验证规则和布局结构。

核心优势
  • Schema 即表单 - 一份 Schema 同时定义数据结构、验证规则和 UI 配置
  • 类型安全 - 完整的 TypeScript 类型推断,从 Schema 到表单数据
  • 零模板代码 - 无需手写 v-for 或重复的表单字段模板

基础示例

创建一个简单的用户注册表单:

邮箱
<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
schemaS

Zod 对象 schema,定义表单字段

state N extends false ? FormState<S> : never

表单状态对象,原地修改。

loadingboolean

外部 loading 状态,与 loadingAuto 的提交中状态合并

submittrueboolean

是否显示默认提交按钮

submitButtonProps ButtonProps

提交按钮属性

addButtonProps ButtonProps

数组字段添加按钮属性

controls AutoFormControls

自定义控件映射

globalMeta ZodAutoFormFieldMeta

全局字段元数据配置

loadingAutotrueboolean

是否启用自动 loading 功能。

validateOn[] FormInputEvents[]

表单验证时机,详见 UForm 的 validateOn 属性

hiddenValue'keep' "clear" | "keep"

字段被 meta.if 隐藏时如何处理其值:keep 保留,clear 置为 undefined;字段 meta 的 hiddenValue 优先。 无论哪种策略,隐藏字段都不参与校验,也不出现在提交数据中

onSubmit (): void | (event: FormSubmitEvent<FormData<S, T>>): void

提交回调;返回 Promise 时配合 loadingAuto 显示加载状态

id string | number
validate (state: Partial<InferInput<S>>): FormError<string>[] | Promise<FormError<string>[]>

Custom validation function to validate the form state.

disabledboolean

Disable all inputs inside the form.

name string

The name attribute of the form element. For nested forms (nested is true), this is also used as the path of the form's state within its parent form.

validateOnInputDelay`300` number

Delay in milliseconds before validating the form on input events.

transform`true` T

If true, applies schema transformations on submit.

nested`false` N

If 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
headerAutoFormSlotProps<AutoFormStateType>
footerAutoFormSlotProps<AutoFormStateType>
submitAutoFormSlotProps<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>
除了组件级别的插槽外,AutoForm 还支持字段级别的动态插槽,并提供完整的 TypeScript 类型推断和编辑器自动补全。
插槽模式示例说明
field-{slotType}field-label, field-default通用插槽,适用于所有字段
field-{slotType}:{fieldKey}field-label:username, field-default:email特定字段插槽,享受完整类型推导
field-{position}:{fieldKey}field-before:profile, field-content:tasks嵌套字段布局插槽

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

您可以通过 useTemplateRef 访问该类型化组件实例。

NameType
reset()void

恢复表单基线并应用 schema 默认值

clear()void

清空表单并保留 schema 默认值

formRefRef<InstanceType<typeof UForm> | null>

UForm 组件的模板引用,可访问底层表单的所有方法和属性

通过 formRef 可以访问 UForm 的所有底层功能,包括 submit()、validate()、clear()、getErrors()、setErrors() 等方法,以及 errors、disabled、dirty、dirtyFields、touchedFields、blurredFields 等响应式属性。详见 Nuxt UI Form 文档。

Theme

app.config.ts
export default defineAppConfig({
  ui: {
    autoForm: {
      slots: {
        root: '',
        base: 'space-y-4',
        collapsible: 'space-y-4',
        header: '',
        footer: '',
        actions: ''
      }
    }
  }
})

Changelog

No recent changes
Copyright © 2025 - 2026 YiXuan - MIT License