JAVASCRIPT
Animating Lists and Dynamic Components with Vue 3 TransitionGroup
Implement smooth enter/leave transitions for lists of elements or dynamic components in Vue 3 using `<TransitionGroup>`, enhancing user experience with fluid animations.
<!-- App.vue -->
<template>
<div>
<h1>Vue 3 TransitionGroup Example</h1>
<button @click="addNumber">Add Number</button>
<button @click="removeNumber">Remove Number</button>
<button @click="shuffleNumbers">Shuffle Numbers</button>
<TransitionGroup name="list" tag="ul">
<li v-for="number in numbers" :key="number">
{{ number }}
</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref } from 'vue';
const numbers = ref([1, 2, 3, 4, 5]);
let nextNumber = 6;
const addNumber = () => {
const randIndex = Math.floor(Math.random() * (numbers.value.length + 1));
numbers.value.splice(randIndex, 0, nextNumber++);
};
const removeNumber = () => {
if (numbers.value.length > 0) {
const randIndex = Math.floor(Math.random() * numbers.value.length);
numbers.value.splice(randIndex, 1);
}
};
const shuffleNumbers = () => {
numbers.value.sort(() => Math.random() - 0.5);
};
</script>
<style>
.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 take up space during transition */
.list-leave-active {
position: absolute;
}
.list-move {
transition: transform 0.5s ease;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<TransitionGroup>` component to animate the insertion, removal, and reordering of elements in a list. By wrapping the `v-for` list with `<TransitionGroup>` and providing a `name` prop, specific CSS classes (`.list-enter-from`, `.list-enter-active`, `.list-leave-to`, etc.) are applied during transitions. The `tag` prop allows rendering a custom element (e.g., `<ul>`), and `:key` is essential for Vue to track individual items for animation, enabling smooth 'move' transitions when items' positions change.