JAVASCRIPT
Animate Element Appearance and Disappearance with Vue 3 Transition
Master creating smooth entrance and exit animations for elements or components in Vue 3 using the built-in `<Transition>` component and CSS transition classes for enhanced UI/UX.
<template>
<div>
<button @click="show = !show">Toggle Box</button>
<Transition name="fade">
<div v-if="show" class="animated-box"></div>
</Transition>
<Transition name="slide-fade">
<p v-if="show">Hello there! I'm a sliding and fading paragraph.</p>
</Transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
</script>
<style scoped>
/* Common styles for the animated box */
.animated-box {
width: 100px;
height: 100px;
background-color: #42b983;
margin-top: 20px;
}
/* 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;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<Transition>` component to add entrance and exit animations to elements or components. Wrap the element you want to animate with `<Transition>` and bind its visibility with `v-if` or `v-show`. The `<Transition>` component automatically applies a set of 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 using the `name` prop (e.g., `name="fade"` generates `fade-enter-...`). By setting CSS `transition` properties on the `-enter-active` and `-leave-active` classes and defining initial/final states with `-enter-from` and `-leave-to`, you can create smooth, custom animations like fading or sliding effects.