Objects and Arrays

Rendering and editing nested object and dynamic array fields.
View source

Object

Difference between two invocation styles
// Direct call
afz.object(shape, meta?)

// Curried call (type parameter `<T>` is for IDE hints only, does not affect runtime validation)
afz.object<T>()(shape, meta?)
const schema = afz.object({
  name: afz.string(),
  age: afz.number()
})

Generic Object

Generic object types are typically combined with selectMenu for selecting complex data structures:

<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>

Nested Object

Nested object structure with collapsible/expandable support:

<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>

Typed Object

Use a TypeScript interface to constrain the object structure, getting IDE field name suggestions when defining the schema:
选择对象类型:
<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>
Three object factories correspond to different extra key handling strategies:
const schema = afz.object({ name: afz.string() })

schema.parse({ name: 'John', extra: 'removed' })
// Result: { name: 'John' }

Array

Use afz.array() to create an array field:

ElementSchema

Defines the type of array elements, determining the output type as T[]:

// String array
const schema1 = afz.array(afz.string())
// Output type: string[]

// Object array
const schema2 = afz.array(afz.object({
  name: afz.string(),
  age: afz.number()
}))
// Output type: { name: string, age: number }[]

Meta

Used to override the default control of array elements and configure metadata, while keeping the output type unchanged:
For object arrays (e.g. afz.array(afz.object({...}))), the system automatically renders using collapsible panels — no need to manually specify a control type.

Without specifying a control type, array elements use the default mapping:

afz.array(afz.string(), {
  label: 'Tag List',
  hint: 'Add multiple tags'
})
// string[] - elements use the input control by default

Async Options and Array Actions

asyncItems reloads choices on deps changes. Pass the supplied signal to the request made by load. Set sortable and duplicable to move and duplicate entries. Schema min, max and length constrain additions and removals.

<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

InputTags component documentation

Tag input field, set type: 'inputTags', suitable for free-text tags:

输入后按 Enter 添加标签
<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

CheckboxGroup component documentation

Checkbox group, set type: 'checkboxGroup', suitable for multi-selecting predefined options:

多选通知方式
<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>

Object Array

Collapsible component documentation

Object arrays are automatically rendered using collapsible panels, supporting add and delete items:

<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>
Copyright © 2025 - 2026 YiXuan - MIT License