JAVASCRIPT
Add Smooth Enter/Leave Transitions to Elements with Vue 3
Implement elegant enter and leave transitions for a single element or component using Vue 3's `<Transition>` component, leveraging CSS classes for animation control.
<template>
<div>
<button @click="show = !show">Toggle Box</button>
<Transition name="fade">
<div v-if="show" class="box"></div>
</Transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
margin-top: 20px;
border-radius: 8px;
}
/* Transition styles */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
How it works: The Vue 3 `<Transition>` component wraps a single element or component and allows you to apply enter/leave transitions when the element is inserted or removed from the DOM. By giving the `<Transition>` component a `name` prop (e.g., `fade`), Vue automatically applies a series of CSS classes (e.g., `.fade-enter-from`, `.fade-enter-active`, `.fade-leave-to`, etc.) during the transition phases. You then define CSS transitions or animations for these classes to create smooth visual effects, such as fading in and out, sliding, or scaling.