JAVASCRIPT

Animating Element Transitions with Vue 3 Transition Component

Add elegant entry and exit animations to elements in your Vue 3 application using the built-in `<transition>` component and CSS transitions for a dynamic user experience.

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

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

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

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

.message {
  padding: 10px;
  background-color: #e0f7fa;
  border: 1px solid #00bcd4;
  border-radius: 4px;
  margin-top: 15px;
  color: #00796b;
}
</style>
How it works: The `<transition>` component in Vue 3 allows you to apply entry/exit animations to elements or components when they are inserted into or removed from the DOM. By wrapping an element with `<transition>` and providing 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`) at different stages of the transition. Developers can then define CSS rules for these classes to create smooth animations, such as the fading effect shown here using `opacity` and `transition` properties.

Need help integrating this into your project?

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

Hire DigitalCodeLabs