JAVASCRIPT
Animating Single Element Toggles with Vue 3's Transition Component
Add smooth show/hide animations to any single element in Vue 3 using the built-in `Transition` component and CSS transitions for better UX.
// FadeToggleComponent.vue
<template>
<div>
<button @click="show = !show">Toggle Message</button>
<Transition name="fade">
<p v-if="show" class="message-box">Hello Vue 3 Transition!</p>
</Transition>
<Transition name="slide-fade">
<div v-if="showAnother" class="another-box">
Another message slides in!
</div>
</Transition>
<button @click="showAnother = !showAnother">Toggle Slide Message</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
const showAnother = ref(false);
</script>
<style scoped>
.message-box {
padding: 15px;
border: 1px solid #ccc;
background-color: #f9f9f9;
margin-top: 10px;
}
/* Fade Transition */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.another-box {
padding: 15px;
border: 1px solid #cce;
background-color: #eef;
margin-top: 10px;
}
/* Slide-Fade Transition */
.slide-fade-enter-active {
transition: all 0.3s ease-out;
}
.slide-fade-leave-active {
transition: all 0.8s 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 apply smooth entry and exit animations to a single element using Vue 3's built-in `<Transition>` component. By wrapping a conditionally rendered element (`v-if`) with `<Transition>` and defining CSS classes for `name-enter-from`, `name-enter-active`, `name-leave-to`, and `name-leave-active`, you can easily create transitions like fade and slide-fade for a more engaging user experience.