Vue Forms 07 ๐ Dynamic Lists & useFieldArray() โ Adding, removing, reordering, and validating repeatable field groups
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
| Method | Description |
|---|---|
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
| Property | Description |
|---|---|
value | Current item data |
key | Unique ID for v-for |
isFieldArray | Boolean flag |
Validation Schema Structure
| Component | Strategy |
|---|---|
| Array | yup.array() |
| Item | yup.object({...}) |
| Nesting | contacts[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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Stale errors | Manual array modification | Use push/remove methods |
| Key collisions | Using array index as key | Use field.key |
| Validation drift | Reordering without swap | Use swap method |
| Schema errors | Incorrect name pathing | Use list[index].prop |
| UI sync issues | Missing key in v-for | Add :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
| Item | Value |
|---|---|
| Function | useFieldArray |
| Mutators | push, remove, swap |
| Identifier | field.key |
| Path Format | array[index].property |
| Validation | Nested yup/zod |
Key takeaways:
- Use the provided mutator methods.
push,remove,swap, andinsertare 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].propertyformat 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
removehelper 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.
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!