Vue Forms 10 ๐ Multi-Step Form Wizards โ Managing multi-page form state, step-by-step schema validation, and persistence
Multi-step forms, or wizards, are a cornerstone of complex data entry in Vue applications. They reduce the cognitive load for users by breaking massive forms into logical segments, such as “Account Info,” “Profile Details,” and “Preferences.” The primary technical challenge is state management: ensuring that data entered on page one is still available when the user reaches page three, and that validation logic respects the current view without interfering with hidden fields.
VeeValidate manages this complexity by centralizing the form state in a parent component using useForm. By utilizing a single form instance, the underlying state remains persistent even as child components (the steps) mount and unmount. This approach decouples your UI navigation from your form data, allowing you to treat the entire wizard as a single, unified source of truth that is incrementally validated as the user progresses.
This chapter covers the architecture of a wizard, how to define schema-based validation for each step, and how to use lifecycle management to prevent data loss. We will also explore the interaction between navigation controls and form progression, ensuring that users can traverse steps confidently while the validation engine enforces rules at every transition.
Key point: A multi-step wizard should be architected with a single useForm instance at the root, allowing child components to focus on rendering their specific step’s fields while the parent manages the centralized state and final submission.
Why useForm wizards exist
The Cognitive Load Problem. Long, single-page forms intimidate users. Wizards allow for granular focus, increasing completion rates by presenting information in bite-sized, manageable chunks.
The State Persistence Problem. Navigating between components often triggers unmount cycles that clear local component state. Centralizing state in the parent prevents data loss during step transitions.
The Validation Granularity Problem. You must allow users to move backward without forcing them to fix errors on the current page, yet block forward progression until the current step is valid. Centralized useForm allows for conditional validation triggers.
The Schema Composition Problem. Complex wizards often require different validation rules per step. Composing schemas based on the current step index keeps validation logic organized and modular.
The Conditional Branching Problem. Wizards often have “forks” (e.g., if you choose ‘Business’, show ‘Tax ID’). Centralized state makes it trivial to hide/show fields and their validation logic based on previous user input.
a. Centralizing state in the parent
To ensure persistence, the useForm instance must reside in the parent container, not in the individual steps. The parent provides the values, errors, and validate function to the steps, acting as a shared context for the entire wizard flow.
// Parent component
const { values, validate } = useForm({
initialValues: { step1: {}, step2: {} }
});
Using <KeepAlive> in your template around your steps is a standard Vue pattern to keep the component state in memory as the user navigates between steps. This works in perfect harmony with VeeValidate, as the fields remain registered in the form instance regardless of whether the component is currently visible in the DOM.
b. Step-by-step validation
You trigger validation for a single step by identifying the fields belonging to that step. By calling validate() and targeting only the path of the current step, you can verify progress before allowing the user to click the “Next” button.
const nextStep = async () => {
const result = await validate({ mode: 'silent' });
if (result.valid) {
currentStep.value++;
}
};
This ensures that the user is not frustrated by errors in later steps, and you maintain complete control over the navigation logic. If the user decides to go back to a previous step, you simply decrement the currentStep index, allowing them to correct data without the UI blocking them with errors from the forward path.
c. Persistence and data structure
Structuring your form data as a nested object is essential for wizards. By prefixing step fields (e.g., step1.email, step2.preferences), you avoid naming collisions and keep the submission payload organized. When the user reaches the final step, you have an object that is already formatted correctly for your API.
// Schema structure
const schemas = [
yup.object({ step1: yup.object({ name: yup.string().required() }) }),
yup.object({ step2: yup.object({ phone: yup.number().required() }) })
];
Persistence is handled by the initialValues property of useForm. If your application requires “Save and Resume” functionality, you can initialize the form with saved data from your database, and VeeValidate will automatically populate the wizard steps, even those that haven’t been visited yet.
Complete Example Session
// ============================================
// PART 1: ROOT FORM INITIALIZATION
// ============================================
import { useForm } from 'vee-validate';
const { handleSubmit, validate } = useForm({
initialValues: { user: {}, address: {} }
});
// ============================================
// PART 2: STEP NAVIGATION
// ============================================
const currentStep = ref(0);
const next = async () => {
const { valid } = await validate();
if (valid) currentStep.value++;
};
// ============================================
// PART 3: STEP COMPONENT
// ============================================
// <Step1 v-if="currentStep === 0" />
// <Step2 v-if="currentStep === 1" />
// ============================================
// PART 4: CONDITIONAL SCHEMAS
// ============================================
// const schema = computed(() => schemas[currentStep.value])
// ============================================
// PART 5: KEEP ALIVE
// ============================================
// <KeepAlive><component :is="currentComponent" /></KeepAlive>
// ============================================
// PART 6: FINAL SUBMISSION
// ============================================
// const onSubmit = handleSubmit(finalValues => api.post(finalValues))
// ============================================
// PART 7: PROGRESS TRACKING
// ============================================
// Computed property for progress bar percentage
// ============================================
// PART 8: BACK NAVIGATION
// ============================================
// const prev = () => currentStep.value--
// ============================================
// PART 9: DATA PERSISTENCE
// ============================================
// Populate via initialValues on component mount
// ============================================
// PART 10: FORM CLEANUP
// ============================================
// resetForm() on completion
This sequence illustrates the lifecycle of a wizard: root-level state, step-based validation checks, and the final submission pattern.
Quick Reference
Wizard Navigation
| Method | Role |
|---|---|
currentStep | Tracks active wizard page |
validate() | Run before incrementing step |
KeepAlive | Prevents component unmount |
initialValues | Resumes saved wizard sessions |
Schema Composition
| Strategy | Benefit |
|---|---|
| Per-step validation | Isolate page errors |
| Nested paths | Clean API payloads |
| Global schema | Full form integrity |
Best Practices
โ Do This:
// Use KeepAlive for smooth transitions
<KeepAlive><component :is="step" /></KeepAlive> // โ
// Validate current step before navigating forward
const { valid } = await validate(); // โ
// Structure data as nested objects for cleanliness
<Field name="step1.email" /> // โ
// Reset after submission
handleSubmit(async (v) => { ...; resetForm(); }); // โ
โ Don’t Do This:
// Don't instantiate useForm in every step
// (State will not persist) // โ
// Don't force validation on back navigation
prev() { currentStep.value-- } // โ
// Don't use flat field names
<Field name="email" /> // Collisions! // โ
// Don't ignore KeepAlive (data lost)
<component :is="step" /> // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Data loss | Components unmounting | Use KeepAlive |
| Navigation block | Invalid validation target | Target specific step path |
| Collisions | Same field names across steps | Use nested dot notation |
| Async lag | Validation not awaited | Use await validate() |
Real-World Examples
1. Validate step
const goNext = async () => { if ((await validate()).valid) step++; };
2. Keep alive wrapper
<KeepAlive><StepOne /></KeepAlive>
3. Nested field name
<Field name="account.username" />
4. Progress tracking
const progress = computed(() => (step / total) * 100);
5. Reset on finish
handleSubmit(save).then(() => resetForm());
6. Conditional rendering
<StepOne v-if="step === 0" />
7. Schema per step
const schema = computed(() => schemas[step.value]);
8. Final submit
const submit = handleSubmit(save);
9. Back navigation
const goBack = () => step.value--;
10. Load saved session
useForm({ initialValues: savedData });
Visual
Wizard Data Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ROOT FORM (useForm) โ
โ โโโ Step 1 (Values: { account: ... }) โ
โ โโโ Step 2 (Values: { profile: ... }) โ
โ โโโ Step 3 (Values: { billing: ... }) โ
โ โ
โ Validations run on step transition โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Navigation Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ [Validate] โโโบ [Success?] โโโบ [Next Step] โ
โ โฒ โ โ
โ โโโโโโโโโโโโโโโ [Back] โโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
State Persistence Logic
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ <KeepAlive> โ
โ <StepOne v-if="step === 0" /> โ
โ <StepTwo v-if="step === 1" /> โ
โ </KeepAlive> โ
โ โ
โ State remains in ROOT FORM โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Root hook | useForm |
| Persistence | KeepAlive |
| Transition | validate() |
| Pathing | Dot notation |
| UI logic | Step index |
Key takeaways:
- Centralize state. The
useFormhook must exist at the parent level, not within individual steps, to ensure data persists during navigation. - Use
KeepAlive. This Vue directive prevents components from unmounting, which protects internal step state and provides a snappier user experience. - Validate transitions. Always
await validate()before allowing the user to move to the next step to ensure data integrity. - Namespace fields. Always use nested paths (e.g.,
stepName.field) to prevent key collisions between disparate steps. - Clean up. Always call
resetFormafter the final submission to clear the wizard’s state for the next user.
Remember: Wizard forms are essentially state machines. By maintaining a single source of truth in the parent and validating progressively, you reduce complexity and create a highly reliable navigation flow. The combination of centralized useForm, KeepAlive, and nested pathing provides a resilient architecture for even the most complex multi-page applications.
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!