← Back to all snippets
JAVASCRIPT

Adding Entry/Exit Animations with Vue 3's `<Transition>` Component

Implement smooth entry and exit transitions for elements in Vue 3 applications using the built-in `<Transition>` component and CSS classes for a polished user experience.

// MyComponent.vue
<template>
  <div>
    <h1>Vue 3 Transition Example</h1>
    <button @click="show = !show">Toggle Message</button>

    <!-- Wrap the element you want to transition with <Transition> -->
    <Transition name="fade">
      <p v-if="show" class="animated-message">
        Hello Vue 3! This message animates in and out.
      </p>
    </Transition>

    <Transition name="slide-fade">
      <div v-if="show" class="animated-box">
        Another animated element, sliding and fading.
      </div>
    </Transition>
  </div>
</template>

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

const show = ref(true);
</script>

<style>
/* CSS for 'fade' transition */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* CSS for '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;
}

.animated-message {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  padding: 10px;
  margin-top: 20px;
  border-radius: 4px;
}

.animated-box {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  padding: 20px;
  margin-top: 20px;
  border-radius: 8px;
  width: 300px;
}
</style>
How it works: The `<Transition>` component in Vue 3 provides a robust way to add entry and exit animations to elements that are being conditionally rendered (e.g., with `v-if` or `v-show`). When an element is inserted or removed, Vue automatically applies specific CSS classes at different stages of the transition. By defining CSS rules for these classes (e.g., `.fade-enter-from`, `.fade-enter-active`, `.fade-leave-to`, `.fade-leave-active`), you can create smooth visual effects. The `name` prop (e.g., `name="fade"`) prefixes these classes, allowing multiple transitions within an application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs