JAVASCRIPT
Dynamically Add and Remove Input Fields in Vue 3 Forms
Create interactive Vue 3 forms that allow users to add new input fields and remove existing ones dynamically, perfect for collecting variable-length data sets like tags or team members.
<template>
<form @submit.prevent="submitForm">
<h3>Add Skills</h3>
<div v-for="(skill, index) in skills" :key="index" class="skill-input">
<input type="text" v-model="skills[index]" placeholder="Enter a skill" required>
<button type="button" @click="removeSkill(index)" v-if="skills.length > 1">Remove</button>
</div>
<button type="button" @click="addSkill">Add Another Skill</button>
<button type="submit">Submit Skills</button>
<pre>{{ submittedSkills }}</pre>
</form>
</template>
<script setup>
import { ref } from 'vue';
const skills = ref(['Vue.js']); // Initialize with one skill
const submittedSkills = ref([]);
const addSkill = () => {
skills.value.push(''); // Add an empty skill input
};
const removeSkill = (index) => {
skills.value.splice(index, 1); // Remove skill at specific index
};
const submitForm = () => {
submittedSkills.value = skills.value.filter(skill => skill.trim() !== ''); // Filter out empty strings
alert('Submitted skills: ' + JSON.stringify(submittedSkills.value));
// In a real app, you would send this data to an API
};
</script>
<style scoped>
form {
max-width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #eee;
border-radius: 8px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
h3 {
color: #333;
margin-bottom: 15px;
}
.skill-input {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
input[type="text"] {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #42b983;
color: white;
}
button[type="button"] {
background-color: #6c757d;
}
button[type="button"]:hover {
background-color: #5a6268;
}
button[type="submit"] {
background-color: #007bff;
margin-top: 15px;
}
button[type="submit"]:hover {
background-color: #0056b3;
}
pre {
background-color: #f8f8f8;
padding: 10px;
border-radius: 4px;
margin-top: 20px;
overflow-x: auto;
}
</style>
How it works: This Vue 3 snippet demonstrates how to create a form with dynamically addable and removable input fields. It uses a `ref` array (`skills`) to hold the values for each input. A `v-for` loop renders an input for each item in the array. The `addSkill` method pushes an empty string to the array, creating a new input, while `removeSkill` uses `splice` to remove an item at a specific index, reflecting the changes reactively in the UI. This pattern is ideal for user interfaces requiring flexible data collection.