---
title: "对象与数组"
description: "嵌套对象与动态数组字段的渲染与增删。"
canonical_url: "https://nuxt.mhaibaraai.cn/docs/auto-form/object-array"
---
# 对象与数组

> 嵌套对象与动态数组字段的渲染与增删。

## Object 对象

> [!NOTE]
> 
> 两种调用方式的区别
> 
> ```ts
> // 直接调用
> afz.object(shape, meta?)
> 
> // 柯里化调用（类型参数 `<T>` 仅用于 IDE 提示，不影响运行时验证。）
> afz.object<T>()(shape, meta?)
> ```
> 
> ```ts
> const schema = afz.object({
>   name: afz.string(),
>   age: afz.number()
> })
> ```
> 
> ```ts
> interface UserInfo {
>   name: string
>   age: number
>   email: string
> }
> 
> const schema = afz.object<UserInfo>()({
>   name: afz.string(),  // IDE 会提示 name | age | email
>   email: afz.email()
> })
> ```

### 通用对象

通用对象类型通常与 `selectMenu` 结合使用，用于选择复杂数据结构：

```vue [AutoFormFieldObjectBasicExample.vue]
<script lang="ts" setup>
import type { FormSubmitEvent } from '@nuxt/ui'
import type { z } from 'zod'

const { afz } = useAutoForm()
const toast = useToast()

const { data: users, execute, pending } = await useLazyFetch('https://jsonplaceholder.typicode.com/users', {
  key: 'typicode-users-basic',
  immediate: false,
  transform: (data: { id: number, name: string }[]) => {
    return data?.map(user => ({
      label: user.name,
      value: String(user.id),
      avatar: { src: `https://i.pravatar.cc/120?img=${user.id}`, loading: 'lazy' as const }
    }))
  }
})

const schema = afz.object({
  name: afz.string().min(1, '请输入姓名').default('张三'),
  age: afz.number().min(1).max(150).default(30),
  email: afz.email('请输入有效的邮箱地址').default('zhangsan@example.com'),
  user: afz.object({
    label: afz.string(),
    value: afz.string(),
    avatar: afz.object({ src: afz.url() })
  }, {
    type: 'selectMenu',
    controlProps: ({ value }: { value: { avatar: { src: string } } }) => ({
      'placeholder': '请选择用户',
      'items': users.value || [],
      'avatar': value?.avatar,
      'loading': pending.value,
      'onUpdate:open': () => {
        if (!users.value && !pending.value) {
          execute()
        }
      }
    })
  })
})

async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
  toast.add({
    title: '提交成功',
    color: 'success',
    description: JSON.stringify(event.data, null, 2)
  })
}
</script>

<template>
  <MAutoForm :schema="schema" @submit="onSubmit" />
</template>
```

### 嵌套对象

嵌套对象结构，支持折叠展开：

```vue [AutoFormFieldObjectNestedExample.vue]
<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({
  user: afz.object({
    name: afz.string(),
    email: afz.email()
  }).meta({ label: '用户信息', collapsible: { defaultOpen: true } }),
  address: afz.object({
    street: afz.string(),
    city: afz.string(),
    zipCode: afz.string()
  }).optional().meta({ label: '地址信息' })
})

async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
  toast.add({
    title: 'Success',
    color: 'success',
    description: JSON.stringify(event.data, null, 2)
  })
}
</script>

<template>
  <MAutoForm :schema="schema" @submit="onSubmit" />
</template>
```

### 类型化对象

> [!TIP]
> 
> 使用 TypeScript 接口约束对象结构，在定义 schema 时获得字段名的 IDE 提示：

```vue [AutoFormFieldObjectTypedExample.vue]
<script lang="ts" setup>
const { afz } = useAutoForm()
const toast = useToast()

interface UserInfo {
  name: string
  age: number
  email: string
}

const userSchema = {
  name: afz.string().min(1, '请输入姓名').default('张三'),
  age: afz.number().min(1).max(150).default(18),
  email: afz.email('请输入有效的邮箱地址').default('example@example.com')
}

const testUser = {
  name: '张三',
  age: 28,
  email: 'test@example.com',
  extraField: '我是额外字段'
}

const normalSchema = afz.object<UserInfo>()(userSchema)
const looseSchema = afz.looseObject<UserInfo>()(userSchema)
const strictSchema = afz.strictObject<UserInfo>()(userSchema)

const currentType = ref<'normal' | 'loose' | 'strict'>('normal')
const items = [
  { label: 'Normal', value: 'normal' },
  { label: 'Loose', value: 'loose' },
  { label: 'Strict', value: 'strict' }
]

const schema = computed(() => {
  switch (currentType.value) {
    case 'loose': return looseSchema
    case 'strict': return strictSchema
    default: return normalSchema
  }
})

async function click() {
  const parsed = schema.value.safeParse(testUser)
  if (!parsed.success) {
    toast.add({
      title: '验证失败',
      color: 'error',
      description: JSON.stringify(parsed.error.issues, null, 2)
    })
  } else {
    toast.add({
      title: '验证成功',
      color: 'success',
      description: JSON.stringify(parsed.data, null, 2)
    })
  }
}
</script>

<template>
  <UCard class="space-y-4">
    <template #header>
      <div class="flex items-center gap-2">
        <span class="text-sm font-medium">选择对象类型：</span>
        <USelect v-model="currentType" :items="items" />
      </div>
    </template>

    <MAutoForm :schema="schema" :submit="false">
      <template #footer>
        <UButton color="primary" @click="click">
          验证类型
        </UButton>
      </template>
    </MAutoForm>
  </UCard>
</template>
```

> [!NOTE]
> 
> 三种对象工厂对应不同的额外字段处理策略：
> 
> ```ts
> const schema = afz.object({ name: afz.string() })
> 
> schema.parse({ name: '张三', extra: 'removed' })
> // 结果：{ name: '张三' }
> ```
> 
> ```ts
> const schema = afz.looseObject({ name: afz.string() })
> 
> schema.parse({ name: '张三', extra: 'kept' })
> // 结果：{ name: '张三', extra: 'kept' }
> ```
> 
> ```ts
> const schema = afz.strictObject({ name: afz.string() })
> 
> schema.parse({ name: '张三', extra: 'error' })
> // 错误：Unrecognized key(s) in object: 'extra'
> ```

## Array 数组

> [!NOTE]
> See: https://zod.dev/api#arrays
> 
> 使用 
> 
> afz.array()
> 
>  创建数组字段：

### ElementSchema

定义数组元素的类型，决定输出类型为 `T[]`：

```ts
// 字符串数组
const schema1 = afz.array(afz.string())
// 输出类型：string[]

// 对象数组
const schema2 = afz.array(afz.object({
  name: afz.string(),
  age: afz.number()
}))
// 输出类型：{ name: string, age: number }[]
```

### Meta

> [!NOTE]
> 
> 用于
> 
> 覆盖数组元素的默认控件
> 
> 和配置元数据，同时保持输出类型不变：

> [!TIP]
> 
> 对于对象数组（如 `afz.array(afz.object({...}))`），系统会自动使用折叠面板渲染，无需手动指定控件类型。
> 
> 不指定控件类型，数组元素使用默认映射：
> 
> ```ts
> afz.array(afz.string(), {
>   label: '标签列表',
>   hint: '添加多个标签'
> })
> // string[] - 元素默认使用 input 控件
> ```
> 
> 通过 `type` 覆盖数组**元素的默认控件**，输出类型保持不变：
> 
> ```ts
> afz.array(afz.string(), {
>   type: 'checkboxGroup',  // 覆盖 string 的默认 input 控件
>   controlProps: {
>     items: ['reading', 'gaming', 'sports']
>   }
> })
> // 输出类型仍为：string[]
> // 但使用 checkboxGroup 渲染（多选）
> ```
> 
> `afz.string()` 本来会被映射为 `input` 控件，通过第二个参数的 `type: 'checkboxGroup'` 覆盖了这个默认映射，将其改为多选框形式。
> 
> 直接传入自定义组件实例：
> 
> ```ts
> import MyArrayControl from './MyArrayControl.vue'
> 
> afz.array(afz.string(), {
>   component: MyArrayControl,
>   controlProps: { /* ... */ }
> })
> ```

### 异步选项与数组操作

`asyncItems` 按 `deps` 重新加载选项，`load` 可将传入的 `signal` 交给请求。`sortable`、`duplicable` 开启数组项移动和复制，`min`、`max` 和 `length` 限制添加与删除。

```vue [AutoFormAsyncItemsArrayExample.vue]
<script setup lang="ts">
import type { AutoFormAsyncItems } from '@movk/nuxt'

const { afz } = useAutoForm()
const cities = { France: ['Lyon', 'Paris'], Japan: ['Kyoto', 'Tokyo'] }
const cityOptions: AutoFormAsyncItems = {
  deps: state => state.country,
  async load({ state }) {
    return state.country === 'Japan' ? cities.Japan : cities.France
  }
}
const schema = afz.object({
  country: afz.enum(['France', 'Japan']).default('France'),
  city: afz.string({ type: 'selectMenu' }).optional().meta({ type: 'selectMenu', asyncItems: cityOptions }),
  tasks: afz.array(afz.string()).min(1).max(4).meta({ sortable: true, duplicable: true })
})
const state = ref({ country: 'France' as 'France' | 'Japan', tasks: ['Draft', 'Review'] })
</script>

<template>
  <MAutoForm v-model="state" :schema="schema" :submit="false" />
</template>
```

### `InputTags`

> [!NOTE]
> See: https://ui.nuxt.com/docs/components/input-tags
> 
> InputTags 组件文档

标签输入框，设置 `type: 'inputTags'`，适合自由文本标签：

```vue [AutoFormFieldArrayInputTagsExample.vue]
<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({
  tags: afz.array(afz.string(), {
    type: 'inputTags'
  })
    .default(['tag1', 'tag2'])
    .meta({
      label: '标签输入',
      hint: '输入后按 Enter 添加标签'
    })
})

async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
  toast.add({
    title: 'Success',
    color: 'success',
    description: JSON.stringify(event.data, null, 2)
  })
}
</script>

<template>
  <MAutoForm :schema="schema" @submit="onSubmit" />
</template>
```

### `CheckboxGroup`

> [!NOTE]
> See: https://ui.nuxt.com/docs/components/checkbox-group
> 
> CheckboxGroup 组件文档

复选框组，设置 `type: 'checkboxGroup'`，适合预定义选项多选：

```vue [AutoFormFieldArrayCheckboxGroupExample.vue]
<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({
  notifications: afz.array(afz.string(), {
    type: 'checkboxGroup',
    controlProps: {
      items: [
        { label: '邮件', value: 'email' },
        { label: '短信', value: 'sms' },
        { label: '电话', value: 'phone' }
      ]
    }
  })
    .default(['email'])
    .meta({
      label: '复选框组',
      hint: '多选通知方式'
    })
})

async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
  toast.add({
    title: 'Success',
    color: 'success',
    description: JSON.stringify(event.data, null, 2)
  })
}
</script>

<template>
  <MAutoForm :schema="schema" @submit="onSubmit" />
</template>
```

### 对象数组

> [!NOTE]
> See: https://ui.nuxt.com/docs/components/collapsible
> 
> Collapsible 组件文档

对象数组自动使用折叠面板渲染，支持添加、删除项：

```vue [AutoFormFieldArrayObjectExample.vue]
<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({
  experience: afz.array(
    afz.object({
      company: afz.string({
        controlProps: {
          placeholder: '公司名称'
        }
      }).min(1).meta({ label: '公司' }),
      position: afz.string({
        controlProps: {
          placeholder: '职位'
        }
      }).min(1).meta({ label: '职位' }),
      years: afz.number({
        controlProps: {
          placeholder: '工作年限'
        }
      }).int().min(0).max(50).meta({ label: '年限', hint: '工作年数' })
    }).meta({ label: '工作经历' })
  ).default([{
    company: '示例公司',
    position: '软件工程师',
    years: 3
  }]).meta({
    label: '工作经历列表',
    collapsible: { defaultOpen: true }
  })
})

async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
  toast.add({
    title: 'Success',
    color: 'success',
    description: JSON.stringify(event.data, null, 2)
  })
}
</script>

<template>
  <MAutoForm :schema="schema" @submit="onSubmit" />
</template>
```


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.cn/sitemap.md) for all pages.
