← Back to all snippets
JAVASCRIPT

Animate Component Entry and Exit with Vue's Transition Component

Create smooth, engaging UI transitions in your Vue 3 applications using the built-in `<Transition>` component to animate elements entering and leaving the DOM with CSS classes.

<template>
  <div>
    <button @click="show = !show">Toggle Message</button>
    <Transition name="fade-slide">
      <p v-if="show" class="message-box">Hello Vue 3 Animations!</p>
    </Transition>

    <button @click="showAlert = !showAlert">Toggle Alert</button>
    <Transition name="bounce">
      <div v-if="showAlert" class="alert-box">This is an animated alert!</div>
    </Transition>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const show = ref(false);
const showAlert = ref(false);
</script>

<style>
/* Fade and Slide 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);
}

/* Bounce Transition */
.bounce-enter-active {
  animation: bounce-in 0.6s;
}
.bounce-leave-active {
  animation: bounce-in 0.6s reverse;
}

@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.message-box, .alert-box {
  background-color: #e0f2f7;
  border: 1px solid #b3e0ed;
  padding: 15px;
  margin-top: 10px;
  border-radius: 5px;
  font-size: 1.1em;
}
.alert-box {
  background-color: #ffe0b2;
  border-color: #ffcc80;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<Transition>` component to apply CSS transitions and animations when an element is inserted or removed from the DOM. By wrapping an element (conditionally rendered with `v-if` or `v-show`) inside a `<Transition>` component and providing a `name` prop, Vue automatically applies specific CSS classes at different stages of the transition (e.g., `name-enter-from`, `name-enter-active`, `name-leave-to`, `name-leave-active`). You can then define CSS rules for these classes to create custom fade, slide, or even keyframe-based bounce effects, making your UI more dynamic and engaging.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs