---
title: "useAutoForm"
description: "用于创建类型化 Zod Schema 和管理 AutoForm 控件的 composable。"
seo_title: "useAutoForm"
seo_description: "Core composable behind AutoForm — exposes the afz Zod factory, defineControl and getAutoFormMetadata."
canonical_url: "https://nuxt.mhaibaraai.cn/docs/composables/use-auto-form"
---
# useAutoForm

> 用于创建类型化 Zod Schema 和管理 AutoForm 控件的 composable。

## 用法

使用自动导入的 `useAutoForm` composable 创建类型化的 Zod Schema，为 [`AutoForm`](/docs/auto-form) 组件提供验证规则和控件配置。

```vue
<script setup lang="ts">
const { afz } = useAutoForm()

const schema = afz.object({
  username: afz.string('用户名不能为空'),
  email: afz.email('请输入有效的邮箱地址'),
  age: afz.number().min(18, '必须年满 18 岁')
})

const formData = ref()
</script>

<template>
  <MAutoForm v-model="formData" :schema="schema" />
</template>
```

- `useAutoForm` 返回增强的 Zod 工厂对象 `afz`，支持为 Schema 附加 AutoForm 元数据。
- 元数据会自动在 Zod 的链式调用中持久化（如 `.optional()`, `.nullable()`, `.default()` 等）。

> \[\!NOTE\]
> 
> 使用 
> 
> afz
> 
>  工厂创建的 Schema 会自动拦截 Zod 的克隆方法，确保元数据在链式调用时不会丢失。

## 自定义控件注册

当使用自定义控件时，需要通过 `defineControl` 辅助函数定义：

```ts
const { afz, defineControl } = useAutoForm({
  myInput: defineControl({
    component: MyCustomInput,
    controlProps: { class: 'w-full' }
  })
})

// 现在可以在 Schema 中使用
const schema = afz.string({
  type: 'myInput',
  controlProps: { variant: 'outline' }
})
```

## API

### useAutoForm()

`useAutoForm(controls?: AutoFormControls): UseAutoFormReturn`

创建 AutoForm 工厂和控件管理器。

#### Parameters

**controls** (`AutoFormControls`): 自定义控件映射对象，用于扩展或覆盖默认控件，配合 defineControl 定义（见上方「自定义控件注册」）。

#### Returns

**afz** (`TypedZodFactory`): 类型化的 Zod 工厂对象，用于创建带元数据的 Schema。

**defineControl** (`Function`): 定义控件的辅助函数。

**DEFAULT\_CONTROLS** (`Object`): 默认控件映射对象。

**controls** (`Object`): 传入的自定义控件映射。

**getAutoFormMetadata** (`Function`): 从 Schema 中提取自定义元数据的工具函数。

## Changelog

See commit history for [src/runtime/composables/useAutoForm.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/useAutoForm.ts).


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
