Multi-step Form
This recipe demonstrates how to use pocket-vue to manage a multi-step form process.
Example Code
html
<div v-scope="{
step: 1,
formData: {
name: '',
email: '',
address: '',
city: ''
},
nextStep() { this.step++ },
prevStep() { this.step-- },
submit() {
console.log('Submitting form:', this.formData)
// Send data to server via fetch
}
}">
<div v-if="step === 1">
<h3>Step 1: Personal Info</h3>
<input v-model="formData.name" placeholder="Name">
<input v-model="formData.email" placeholder="Email">
<button @click="nextStep">Next</button>
</div>
<div v-else-if="step === 2">
<h3>Step 2: Address Info</h3>
<input v-model="formData.address" placeholder="Address">
<input v-model="formData.city" placeholder="City">
<button @click="prevStep">Back</button>
<button @click="nextStep">Next</button>
</div>
<div v-else-if="step === 3">
<h3>Step 3: Confirm</h3>
<p>Name: {{ formData.name }}</p>
<p>Email: {{ formData.email }}</p>
<p>Address: {{ formData.address }}, {{ formData.city }}</p>
<button @click="prevStep">Back</button>
<button @click="submit">Confirm & Submit</button>
</div>
</div>How it works
- State Management: We use a single
stepvariable to track the current stage of the form and aformDataobject to store all user inputs. - Conditional Rendering: We use
v-if,v-else-if, andv-elseto display only the relevant section of the form for the current step. - Step Navigation: We provide
nextStepandprevStepmethods to increment or decrement thestepvariable. - Preserved State: Because
formDatais defined in the root scope, all user inputs are preserved as they move between steps. - Summary View: In the final step, we can easily display a summary of all entered data before submission.
