JAVASCRIPT
Animating List Item Transitions with Vue 3 TransitionGroup
Enhance user experience by smoothly animating the addition, removal, and reordering of items in dynamic lists using Vue 3's <TransitionGroup> component and CSS transitions.
<!-- App.vue -->
<template>
<div>
<h1>Todo List with Animations</h1>
<input v-model="newItem" @keyup.enter="addItem" placeholder="Add a new todo" />
<button @click="addItem">Add Todo</button>
<TransitionGroup name="list" tag="ul">
<li v-for="(item, index) in items" :key="item.id">
{{ item.text }}
<button @click="removeItem(index)">Remove</button>
</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref } from 'vue';
let id = 0;
const newItem = ref('');
const items = ref([
{ id: id++, text: 'Learn Vue 3' },
{ id: id++, text: 'Build a project' },
{ id: id++, text: 'Deploy to Netlify' }
]);
function addItem() {
if (newItem.value.trim() !== '') {
items.value.push({ id: id++, text: newItem.value });
newItem.value = '';
}
}
function removeItem(index) {
items.value.splice(index, 1);
}
</script>
<style>
/* Define transition classes based on 'name' prop of TransitionGroup */
.list-enter-active, .list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from, .list-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* Ensure leaving items don't affect layout during transition */
.list-leave-active {
position: absolute;
width: calc(100% - 20px); /* Adjust based on parent padding/margin */
}
/* Transition for moving items */
.list-move {
transition: transform 0.5s ease;
}
/* Basic styling for list */
ul {
list-style: none;
padding: 0;
margin-top: 20px;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
margin-bottom: 5px;
background-color: #f9f9f9;
border: 1px solid #eee;
border-radius: 4px;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<TransitionGroup>` component to add smooth animations to dynamic lists. By wrapping a `v-for` rendered list inside `<TransitionGroup>`, Vue automatically applies CSS transition classes (like `list-enter-from`, `list-enter-active`, `list-leave-to`, `list-leave-active`, `list-move`) when items are added, removed, or reordered. The associated CSS defines the actual transition properties for opacity and transform, making the list items appear, disappear, and shuffle gracefully. The `key` prop on `v-for` is crucial for `<TransitionGroup>` to track individual items efficiently.