| | |

Vue Forms 07 ๐Ÿ“ Dynamic Lists & useFieldArray() โ€” Adding, removing, reordering, and validating repeatable field groups

โฑ๏ธ Estimated read: 8 min | |

Dynamic formsโ€”where users can add, remove, or reorder entriesโ€”are a common requirement in data-heavy applications. Whether you are building an invoice with infinite line items, an address manager, or a collaborative survey, managing the state and validation of these arrays manually is error-prone. VeeValidate provides the useFieldArray composition function specifically to treat collections of fields as a single, manageable reactive unit, ensuring that validation rules and state tracking remain consistent even as the list structure changes.

When you use useFieldArray, you are not just managing an array of values; you are managing an array of validation states. The function tracks the index of every item, ensuring that if you remove the second item in a list of five, the third, fourth, and fifth items are automatically shifted and re-validated. This abstraction layer is what makes complex, dynamic forms manageable, as it handles the heavy lifting of indexing and reactive DOM updates behind the scenes.

This chapter covers the mechanics of initializing arrays, manipulating them with built-in helper methods like push and remove, and managing complex validation schemas where each item in the array requires its own constraints. We will also explore how to bind these dynamic fields to your UI, ensuring that your user interface stays in perfect sync with the underlying form state.

Key point: useFieldArray transforms a standard JavaScript array into a reactive, validated collection where every addition, removal, or swap triggers necessary re-validation across the set, maintaining the integrity of form indices.


Why useFieldArray exists

The Indexing Problem. Manually managing indices when removing or reordering items in a list of inputs often leads to “ghost” validation errors. useFieldArray ensures that indices are handled internally by VeeValidate, preventing mismatched state.

The State Bloat Problem. In a dynamic form, adding a new group of inputs requires registering multiple new fields. useFieldArray provides a centralized API to manage this, preventing the need to manually track dozens of individual field registrations.

The Validation Consistency Problem. When a list item is removed, the associated error messages must also disappear. useFieldArray provides a clean cleanup mechanism that automatically clears the validation state of any field that is removed from the DOM.

The Reordering Complexity. Moving an item from the bottom of a list to the top causes the data and validation rules to drift if not handled correctly. The swap and move methods in useFieldArray ensure that the associated metadata (like touched and dirty status) follows the item correctly.

The Schema Integration. When validating an array, you often need to validate the list as a whole (e.g., “must have at least one item”) while also validating the specific properties of each item. useFieldArray enables nested validation schemes that work seamlessly with yup or zod.


a. Initializing the array and accessing fields

You initialize useFieldArray by passing the name of the array field. The function returns a fields ref, which contains the current list of items, along with helper methods to modify that list. Each field in the array is an object containing the key and internal state.

import { useFieldArray, useForm } from 'vee-validate';

const { defineField } = useForm();
const { fields, push, remove } = useFieldArray('users');

// fields is a reactive array of objects
// { value, key, isFieldArray }

The fields object is a computed ref. You iterate over fields.value in your template. It is critical to use the key provided by the array items in your v-for loop. This ensures that Vue correctly maps the DOM elements to the reactive form state, preventing bugs during deletions or reorders.


b. Modifying the list with helper methods

useFieldArray exposes a suite of methods to manipulate the array structure. These methods are designed to be used in event handlers. For example, push adds an object to the end of the list, while remove deletes an item at a specific index.

const addUser = () => {
  push({ name: '', email: '' }); // Adds an empty schema object
};

const removeUser = (index: number) => {
  remove(index); // Removes the item and cleans up validation
};

These methods are strictly necessary because they notify VeeValidate of the change. If you were to manually modify the underlying array data without these methods, VeeValidate would lose track of the field registrations, leading to broken validation logic and stale error states in the UI.


c. Schema-based dynamic validation

Validating dynamic lists requires a nested schema. Using a library like yup, you define the schema for the array as a whole, which then validates the objects inside the array. This keeps the form logic clean and centralized, rather than scattering rules across individual components.

import * as yup from 'yup';

const schema = yup.object({
  users: yup.array().of(
    yup.object({
      name: yup.string().required(),
      email: yup.string().email().required()
    })
  )
});

When you call validate() on the form, VeeValidate traverses the array and checks each index against the schema. Because useFieldArray keeps the indices accurate, error messages are mapped correctly to the specific input field in the list, providing the user with direct feedback on which row is invalid.


Complete Example Session

// ============================================
// PART 1: SETUP FORM AND ARRAY
// ============================================
import { useForm, useFieldArray } from 'vee-validate';
const { handleSubmit } = useForm();
const { fields, push, remove } = useFieldArray('contacts');

// ============================================
// PART 2: ADDING AN ITEM
// ============================================
const addContact = () => push({ name: '', phone: '' });

// ============================================
// PART 3: REMOVING AN ITEM
// ============================================
const removeContact = (idx: number) => remove(idx);

// ============================================
// PART 4: TEMPLATE ITERATION
// ============================================
// <div v-for="(field, idx) in fields" :key="field.key">
//   <Field :name="`contacts[${idx}].name`" />
// </div>

// ============================================
// PART 5: NESTED VALIDATION (YUP)
// ============================================
// yup.array().of(yup.object({ name: yup.string().required() }))

// ============================================
// PART 6: ACCESSING VALUES
// ============================================
// fields.value returns the array of items

// ============================================
// PART 7: REORDERING
// ============================================
// swap(0, 1)

// ============================================
// PART 8: INITIAL VALUES
// ============================================
// useForm({ initialValues: { contacts: [{ name: 'Test' }] } })

// ============================================
// PART 9: ERROR ACCESS
// ============================================
// Use `errors` from useForm to find nested issues

// ============================================
// PART 10: SUBMISSION
// ============================================
// const onSubmit = handleSubmit(values => console.log(values))

This sequence provides a complete workflow: initializing the dynamic form, handling list mutations with helper methods, and mapping those to a robust validation schema.


Quick Reference

Array Mutator Methods

MethodDescription
push(val)Add item to end of list
remove(idx)Remove item at index
swap(i, j)Swap positions of two items
insert(idx, val)Add item at specific index
replace(arr)Overwrite entire array

Field Object Properties

PropertyDescription
valueCurrent item data
keyUnique ID for v-for
isFieldArrayBoolean flag

Validation Schema Structure

ComponentStrategy
Arrayyup.array()
Itemyup.object({...})
Nestingcontacts[0].name

Best Practices

โœ… Do This:

// Use the unique key provided by the fields object
<div v-for="field in fields" :key="field.key"></div>        // โœ…

// Always use index-based names for Field components
<Field :name="`list[${idx}].prop`" />                      // โœ…

// Define schemas to validate the whole array
const schema = yup.object({ items: yup.array().of(...) });  // โœ…

// Use push for adding empty shells
push({ name: '' });                                         // โœ…

โŒ Don’t Do This:

// Don't use array index as key in v-for
<div v-for="(f, i) in fields" :key="i"></div>               // โŒ

// Don't manually modify the array data
list.value.push(item);                                      // โŒ

// Don't define local states for array items
const local = ref([]);                                      // โŒ

// Don't forget to define the name attribute in Field
<Field />                                                   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Stale errorsManual array modificationUse push/remove methods
Key collisionsUsing array index as keyUse field.key
Validation driftReordering without swapUse swap method
Schema errorsIncorrect name pathingUse list[index].prop
UI sync issuesMissing key in v-forAdd :key="field.key"

Real-World Examples

1. Add item

push({ title: '' });

2. Remove by index

remove(index);

3. Swap two items

swap(0, 1);

4. Template Field binding

<Field :name="`items[${idx}].name`" />

5. Validation Schema

yup.array().of(yup.object({ name: yup.string() }));

6. Initial Values

useForm({ initialValues: { list: [{ id: 1 }] } });

7. Array length check

yup.array().min(1, 'Need one item');

8. Field access

const { fields } = useFieldArray('list');

9. Clear all

replace([]);

10. Insert at start

insert(0, { title: 'New' });

Visual

The FieldArray Structure

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  useFieldArray("items")                      โ”‚
โ”‚                                              โ”‚
โ”‚  items[0] โ”€โ–บ value โ”€โ–บ validation engine      โ”‚
โ”‚  items[1] โ”€โ–บ value โ”€โ–บ validation engine      โ”‚
โ”‚  items[2] โ”€โ–บ value โ”€โ–บ validation engine      โ”‚
โ”‚                                              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The v-for Mapping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  <div v-for="field in fields" :key="field.key">
โ”‚    <Field :name="`items[${idx}].val`" />     โ”‚
โ”‚  </div>                                      โ”‚
โ”‚                                              โ”‚
โ”‚  - field.key ensures reactivity              โ”‚
โ”‚  - Field name maps to array path             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Mutator Effect

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  [A, B, C] โ”€โ”€remove(1)โ”€โ”€โ–บ [A, C]             โ”‚
โ”‚                                              โ”‚
โ”‚  - index 2 becomes index 1                   โ”‚
โ”‚  - validation state for C shifts             โ”‚
โ”‚  - error messages update accordingly         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
FunctionuseFieldArray
Mutatorspush, remove, swap
Identifierfield.key
Path Formatarray[index].property
ValidationNested yup/zod

Key takeaways:

  • Use the provided mutator methods. push, remove, swap, and insert are essential for keeping VeeValidateโ€™s internal state in sync with your data.
  • Always use field.key. This is the only way to prevent re-rendering bugs and incorrect state mapping when lists are modified.
  • Use dot notation paths. VeeValidate relies on path[index].property format to correctly associate validation errors with specific inputs.
  • Schema-based validation is preferred. Centralizing rules for array items in a parent schema keeps the code maintainable and prevents redundant rule definitions.
  • Array cleanup is automatic. Removing an item with the remove helper automatically disposes of its associated validation errors and metadata.

Remember: useFieldArray is the backbone of dynamic form building in VeeValidate. By treating your lists as reactive collections rather than arbitrary data structures, you gain powerful synchronization, automated error handling, and simplified DOM management. Always prioritize the provided array methods to ensure the internal integrity of your form state remains robust throughout the entire lifecycle of the component.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!