Vue Forms 12 ๐ Cheatsheet
1. Composition API Primitives
The foundation of form handling.
| Function | Signature | Use Case |
|---|---|---|
useForm | useForm(config?) | Root initialization; centralized state. |
useField | useField(name, rules?, opts?) | Binding individual inputs to validation. |
useFieldArray | useFieldArray(name) | Reactive management of lists/repetitive data. |
handleSubmit | handleSubmit(fn) | Form submission helper (handles validation). |
setErrors | setErrors(obj) | Injects external (API) errors into form. |
resetForm | resetForm(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
| Technique | Implementation | Benefit |
|---|---|---|
| Manual Triggers | validateOnValueUpdate: false | Stops validation on every keystroke. |
| Memoization | v-memo="[meta.valid]" | Prevents re-rendering clean UI blocks. |
| Shallow Refs | shallowRef(complexObject) | Reduces proxy overhead for large forms. |
| Pending State | meta.pending | UX 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 forv-iftoggling). - Data: Store in
initialValuesof parentuseForm.
- Parent:
5. Testing Infrastructure Cheat Sheet
Using @testing-library/vue and Vitest.
| Action | Command | Note |
|---|---|---|
| Simulate Input | await fireEvent.update(input, 'val') | Updates reactive state. |
| Simulate Blur | await fireEvent.blur(input) | Triggers validation logic. |
| Wait for DOM | await screen.findByText(/error/) | Crucial for async/reactive updates. |
| Assert Call | expect(spy).toHaveBeenCalledWith(data) | Verifies API payload structure. |
| Clean Up | vi.restoreAllMocks() | Prevents test cross-contamination. |
6. Common Patterns Matrix
| Problem | Pattern | Best Method |
|---|---|---|
| Infinite inputs | useFieldArray | push, remove, swap |
| Form Wizard | Parent useForm | KeepAlive + Step index |
| Async Logic | Debounced Rule | Promise return + try/catch |
| UI Stutter | Manual trigger | validateOnValueUpdate: false |
| Data Loss | Dirty tracking | window.onbeforeunload + meta.dirty |
7. Configuration Reference Table
| Field Option | Default | Purpose |
|---|---|---|
initialValue | undefined | Defines starting state. |
validateOnBlur | true | Runs validation on loss of focus. |
validateOnInput | true | Runs validation on every character. |
validateOnChange | true | Runs on generic change events. |
keepValueOnUnmount | false | Keeps value if field removed from DOM. |
8. Master Pitfall Prevention
- Field Registration: If
useFieldis in a loop, ensure a unique name (e.g.,names[${i}]) or the state will collide. - Schema Mismatch: Always mirror the API object shape in the Schema; if the API expects
{ user: { age: 1 } }, the Field name must beuser.age. - Submit Failures: If
handleSubmitdoesn’t trigger, verify no validation rule is returning an error you aren’t seeing (checkerrors.value). - Async Race Conditions: Never assume the last typed character results in the last API call; always debounce or abort previous requests.
- Re-rendering: Avoid putting
useFieldinside a deeply nested recursive component tree without memoization, as it creates a large reactive dependency graph.
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!