JAVASCRIPT
Animating Elements with Vue 3's `<Transition>` Component
Implement smooth entry/leave animations for elements or components in Vue 3 using the built-in `<Transition>` component and CSS transitions, significantly enhancing the user experience.
// App.vue
<template>
<div>
<button @click="show = !show">Toggle Element</button>
<Transition name="fade">
<p v-if="show" class="animated-box">Hello Vue 3 Animations!</p>
</Transition>
<button @click="isVisible = !isVisible" style="margin-top: 20px;">Toggle Block</button>
<Transition name="slide-fade">
<div v-if="isVisible" class="animated-block">
This block slides and fades.
</div>
</Transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
const isVisible = ref(true);
</script>
<style>
/* Fade Transition */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
/* Slide-Fade Transition */
.slide-fade-enter-active {
transition: all 0.5s ease-out;
}
.slide-fade-leave-active {
transition: all 0.5s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter-from,
.slide-fade-leave-to {
transform: translateX(20px);
opacity: 0;
}
.animated-box, .animated-block {
background-color: #42b983;
color: white;
padding: 10px 20px;
border-radius: 5px;
margin-top: 10px;
display: inline-block; /* For animated-box */
}
.animated-block {
width: 200px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's built-in `<Transition>` component to add entry and leave animations to elements. By wrapping an element with `<Transition>` and giving it a `name` prop (e.g., "fade", "slide-fade"), Vue automatically applies specific CSS classes at different stages of the transition (e.g., `fade-enter-from`, `fade-enter-active`, `fade-leave-to`). You then define CSS rules for these classes to create desired visual effects like fading opacity or sliding movement, enhancing user experience during element toggling.