| | |

Vue Forms 12 ๐Ÿ“ Cheatsheet

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

1. Composition API Primitives

The foundation of form handling.

FunctionSignatureUse Case
useFormuseForm(config?)Root initialization; centralized state.
useFielduseField(name, rules?, opts?)Binding individual inputs to validation.
useFieldArrayuseFieldArray(name)Reactive management of lists/repetitive data.
handleSubmithandleSubmit(fn)Form submission helper (handles validation).
setErrorssetErrors(obj)Injects external (API) errors into form.
resetFormresetForm(opts?)Clears errors, values, and resets metadata.

2. Advanced Pathing & Schema Integration

Mastering nested data structures and cross-field logic.

Path Syntax Patterns

  • Nested: user.profile.address.zip
  • Indexed: items[0].name
  • Dynamic: items[${index}].quantity
  • Multi-step: step1.email / step2.preferences

Schema Composition (Yup/Zod Examples)

  • Conditional Required: email: yup.string().when('newsletter', { is: true, then: (s) => s.required(), otherwise: (s) => s.optional() })
  • Cross-Field Matching:confirm: yup.string().oneOf([yup.ref('password')], 'Must match password')
  • Array Validation:list: yup.array().of(yup.object({ name: yup.string().required() }))

3. Performance & Async Optimization

Handling the trade-offs of server-side validation and reactivity.

Debouncing Logic (Manual/Lodash)

import { debounce } from 'lodash-es';
// Only triggers after 500ms of inactivity
const debouncedValidation = debounce(async (val) => {
  await validateField('username');
}, 500);

Performance Optimization Tactics

TechniqueImplementationBenefit
Manual TriggersvalidateOnValueUpdate: falseStops validation on every keystroke.
Memoizationv-memo="[meta.valid]"Prevents re-rendering clean UI blocks.
Shallow RefsshallowRef(complexObject)Reduces proxy overhead for large forms.
Pending Statemeta.pendingUX indicator during long network requests.

4. Lifecycle & Server Interaction

How to move data from API to Form and vice-versa.

  • Handling 422 Errors:catch (e) { setErrors({ 'field.path': e.response.data.message }); }
  • Tracking Dirty State:
    • meta.dirty: Modified from initial.
    • meta.touched: Has lost focus.
    • meta.pending: Async work in progress.
  • Wizard Persistence:
    • Parent: useForm
    • Children: <KeepAlive> (essential for v-if toggling).
    • Data: Store in initialValues of parent useForm.

5. Testing Infrastructure Cheat Sheet

Using @testing-library/vue and Vitest.

ActionCommandNote
Simulate Inputawait fireEvent.update(input, 'val')Updates reactive state.
Simulate Blurawait fireEvent.blur(input)Triggers validation logic.
Wait for DOMawait screen.findByText(/error/)Crucial for async/reactive updates.
Assert Callexpect(spy).toHaveBeenCalledWith(data)Verifies API payload structure.
Clean Upvi.restoreAllMocks()Prevents test cross-contamination.

6. Common Patterns Matrix

ProblemPatternBest Method
Infinite inputsuseFieldArraypush, remove, swap
Form WizardParent useFormKeepAlive + Step index
Async LogicDebounced RulePromise return + try/catch
UI StutterManual triggervalidateOnValueUpdate: false
Data LossDirty trackingwindow.onbeforeunload + meta.dirty

7. Configuration Reference Table

Field OptionDefaultPurpose
initialValueundefinedDefines starting state.
validateOnBlurtrueRuns validation on loss of focus.
validateOnInputtrueRuns validation on every character.
validateOnChangetrueRuns on generic change events.
keepValueOnUnmountfalseKeeps value if field removed from DOM.

8. Master Pitfall Prevention

  1. Field Registration: If useField is in a loop, ensure a unique name (e.g., names[${i}]) or the state will collide.
  2. Schema Mismatch: Always mirror the API object shape in the Schema; if the API expects { user: { age: 1 } }, the Field name must be user.age.
  3. Submit Failures: If handleSubmit doesn’t trigger, verify no validation rule is returning an error you aren’t seeing (check errors.value).
  4. Async Race Conditions: Never assume the last typed character results in the last API call; always debounce or abort previous requests.
  5. Re-rendering: Avoid putting useField inside a deeply nested recursive component tree without memoization, as it creates a large reactive dependency graph.

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!