JAVASCRIPT
Dynamically Add/Remove Input Fields in Vue 3
Discover how to manage dynamic lists of input fields in Vue 3, allowing users to add or remove items efficiently using the Composition API.
<template>
<div>
<h3>Dynamic To-Do List</h3>
<div v-for="(todo, index) in todos" :key="todo.id" class="todo-item">
<input type="text" v-model="todo.text" :placeholder="`Todo ${index + 1}`" />
<button @click="removeTodo(index)" class="remove-button">Remove</button>
</div>
<button @click="addTodo" class="add-button">Add To-Do</button>
<pre>Current Todos: {{ JSON.stringify(todos, null, 2) }}</pre>
</div>
</template>
<script setup>
import { ref } from 'vue';
const todos = ref([]);
let nextId = 0;
function addTodo() {
todos.value.push({ id: nextId++, text: '' });
}
function removeTodo(index) {
todos.value.splice(index, 1);
}
// Initialize with a few items
addTodo();
addTodo();
</script>
<style scoped>
.todo-item {
display: flex;
gap: 10px;
margin-bottom: 8px;
align-items: center;
}
.add-button {
margin-top: 15px;
padding: 8px 15px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.remove-button {
padding: 6px 10px;
background-color: #e74c3c;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
flex-grow: 1;
}
pre {
background-color: #f4f4f4;
padding: 10px;
border-radius: 4px;
margin-top: 20px;
white-space: pre-wrap;
}
</style>
How it works: This snippet demonstrates how to create a dynamic list of input fields where users can add or remove items. It uses Vue's `ref` to manage a reactive array of `todos`. The `addTodo` method pushes new objects into the array, each with a unique `id` and `text`. The `removeTodo` method uses `splice` to remove an item by its index. `v-for` efficiently renders and updates the list, with `:key="todo.id"` being crucial for performance and state preservation during list manipulations.