JAVASCRIPT
Animating Vue 3 Components with the Transition Component
Learn to use Vue 3's built-in <Transition> component to add smooth entering and leaving animations to elements or components based on conditional rendering.
<template>
<div>
<button @click="showBox = !showBox">Toggle Box</button>
<Transition name="fade-slide">
<div v-if="showBox" class="animated-box">
Hello, Vue 3 Transitions!
</div>
</Transition>
<button @click="showList = !showList">Toggle List</button>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item.id" class="list-item">
{{ item.text }}
</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
const showBox = ref(false);
const showList = ref(true); // For TransitionGroup example
const initialItems = [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
];
const allItems = reactive([...initialItems]);
const items = computed(() => showList.value ? allItems : []);
// Add/remove items for demonstration, e.g., via a button
// This example uses a computed property to simulate adding/removing items
</script>
<style>
/* Styles for the single element transition */
.fade-slide-enter-active,
.fade-slide-leave-active {
transition: opacity 0.5s ease, transform 0.5s ease;
}
.fade-slide-enter-from,
.fade-slide-leave-to {
opacity: 0;
transform: translateY(20px);
}
/* Styles for the list transition (TransitionGroup) */
.list-enter-active,
.list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* Ensures list items don't jump when one is removed */
.list-move {
transition: transform 0.5s ease;
}
/* General styling for animated elements */
.animated-box {
background-color: #42b983;
color: white;
padding: 20px;
margin-top: 20px;
border-radius: 8px;
width: 200px;
text-align: center;
}
.list-item {
background-color: #35495e;
color: white;
padding: 10px;
margin-bottom: 5px;
border-radius: 4px;
}
</style>
How it works: Vue 3's `<Transition>` component is used to add entrance and exit animations to elements or components that are conditionally rendered with `v-if`, `v-show`, or dynamic components. You define CSS transitions or animations using specific CSS classes (e.g., `v-enter-from`, `v-enter-active`, `v-leave-to`) based on the `name` prop. For animating list items (`v-for`), `<TransitionGroup>` is used to handle insertions, removals, and reordering, requiring a `key` prop on each direct child and providing additional transition classes like `-move`.