JAVASCRIPT
Handling Dynamic Form Fields with Reactive Arrays
Learn to effectively manage a dynamic list of form inputs in Vue 3 using reactive arrays, enabling users to add, remove, and update multiple items seamlessly.
<template>
<div>
<h1>Skills List</h1>
<form @submit.prevent="submitSkills">
<div v-for="(skill, index) in skills" :key="index" class="skill-item">
<label>Skill Name:</label>
<input type="text" v-model="skill.name" placeholder="e.g., JavaScript" required />
<label>Proficiency:</label>
<input type="number" v-model="skill.proficiency" min="1" max="5" required />
<button type="button" @click="removeSkill(index)" class="remove-button">Remove</button>
</div>
<button type="button" @click="addSkill" class="add-button">Add Skill</button>
<button type="submit" class="submit-button">Submit All Skills</button>
</form>
<pre>{{ JSON.stringify(skills, null, 2) }}</pre>
</div>
</template>
<script setup>
import { reactive } from 'vue';
const skills = reactive([
{ name: 'Vue.js', proficiency: 4 },
{ name: 'CSS', proficiency: 3 }
]);
const addSkill = () => {
skills.push({ name: '', proficiency: 1 });
};
const removeSkill = (index) => {
skills.splice(index, 1);
};
const submitSkills = () => {
console.log('Submitted Skills:', skills);
alert('Skills submitted! Check console for data.');
// Here you would typically send `skills` data to an API
};
</script>
<style scoped>
.skill-item {
display: flex;
gap: 10px;
align-items: center;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #eee;
border-radius: 4px;
background-color: #f9f9f9;
}
.skill-item input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
flex-grow: 1;
}
.remove-button, .add-button, .submit-button {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.remove-button {
background-color: #dc3545;
color: white;
}
.add-button {
background-color: #007bff;
color: white;
margin-top: 15px;
}
.submit-button {
background-color: #28a745;
color: white;
margin-left: 10px;
margin-top: 15px;
}
</style>
How it works: This snippet demonstrates how to manage a dynamic list of form inputs using a `reactive` array in Vue 3. Each object in the `skills` array represents a single skill with its `name` and `proficiency`. The `v-for` directive iterates over this array, creating a pair of input fields for each skill. `v-model` is used for two-way binding, automatically updating the corresponding `skill` object in the `skills` array when input values change. Buttons are provided to `addSkill` (push a new empty skill object) and `removeSkill` (splice an item from the array), showcasing how Vue's reactivity system efficiently updates the UI in response to array mutations.