JAVASCRIPT
Animate List Items with Vue 3's TransitionGroup Component
Create smooth enter/leave and reordering animations for lists of elements in Vue 3 using the powerful `<TransitionGroup>` component and CSS transitions.
<template>
<div>
<button @click="shuffleList">Shuffle Items</button>
<button @click="addItem">Add Item</button>
<button @click="removeItem">Remove Item</button>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, text: 'Item A' },
{ id: 2, text: 'Item B' },
{ id: 3, text: 'Item C' }
]);
let nextId = 4;
const shuffleList = () => {
items.value.sort(() => Math.random() - 0.5);
};
const addItem = () => {
const newItem = { id: nextId++, text: `Item ${String.fromCharCode(64 + nextId)}` };
const randomIndex = Math.floor(Math.random() * (items.value.length + 1));
items.value.splice(randomIndex, 0, newItem);
};
const removeItem = () => {
if (items.value.length > 0) {
const randomIndex = Math.floor(Math.random() * items.value.length);
items.value.splice(randomIndex, 1);
}
};
</script>
<style>
/* Define CSS transitions for the 'list' transition group */
.list-enter-active, .list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from, .list-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* Ensure that leaving elements don't affect layout during transition */
.list-leave-active {
position: absolute;
}
/* Apply 'move' transition for elements that change position */
.list-move {
transition: transform 0.5s ease;
}
/* Basic styling for the list items */
ul {
list-style-type: none;
padding: 0;
margin-top: 20px;
}
li {
background-color: #f0f0f0;
padding: 10px;
margin-bottom: 5px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
width: 150px;
height: 40px;
}
button {
margin: 5px;
padding: 8px 15px;
cursor: pointer;
}
</style>
How it works: This snippet demonstrates how to animate list item additions, removals, and reordering using Vue 3's `<TransitionGroup>` component. By wrapping a `v-for` list inside `<TransitionGroup>`, Vue automatically applies CSS classes (`list-enter-from`, `list-enter-active`, `list-leave-to`, `list-leave-active`, `list-move`) at different stages of the transition. The accompanying CSS defines actual transitions for opacity, transform, and position, creating a smooth visual experience for dynamic lists. The `tag='ul'` prop ensures the `<TransitionGroup>` renders as a `<ul>` element, while `position: absolute` for `.list-leave-active` prevents layout shifts during removals.