JAVASCRIPT

Animating Element Transitions with Vue's <Transition> Component

Implement smooth enter/leave animations for elements or components using Vue 3's built-in <Transition> component and CSS transitions for dynamic UIs.

// App.vue
<template>
  <div>
    <h1>Vue Transition Example</h1>
    <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, this is a sliding and fading paragraph!</p>
    </Transition>
  </div>
</template>

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

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

<style>
/* Common styles for the box */
.animated-box {
  width: 100px;
  height: 100px;
  background-color: crimson;
  margin-top: 20px;
  border-radius: 8px;
}

/* 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.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 use Vue 3's `<Transition>` component to add enter/leave animations to elements. By wrapping an element with `<Transition>` and giving it a `name` prop (e.g., `fade` or `slide-fade`), Vue automatically applies specific CSS classes at different stages of the transition (e.g., `.fade-enter-from`, `.fade-enter-active`, `.fade-leave-to`). These classes can then be targeted with CSS to define transition properties like `opacity`, `transform`, and `transition` duration, creating smooth visual effects when elements are conditionally rendered or removed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs