JAVASCRIPT

Smoothly Animating Element Transitions with Vue 3 <Transition> Component

Discover how to use Vue 3's built-in <Transition> component with CSS classes to create elegant enter and leave animations for elements in your application.

// MyComponent.vue
<template>
  <div>
    <button @click="show = !show">Toggle Message</button>
    <Transition name="fade">
      <p v-if="show" class="message">Hello, Vue 3 Transitions!</p>
    </Transition>
  </div>
</template>

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

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

<style>
/* Define transition 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: 15px;
  background-color: #e0f7fa;
  border: 1px solid #00bcd4;
  border-radius: 5px;
  margin-top: 20px;
  text-align: center;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<Transition>` component to animate the appearance and disappearance of an element. By wrapping an element with `<Transition>` and binding its visibility to `v-if` (or `v-show`), Vue automatically applies specific CSS classes at different stages of the transition. The CSS rules for `.fade-enter-active`, `.fade-leave-active`, `.fade-enter-from`, and `.fade-leave-to` define the actual animation, in this case, a simple fade effect. This provides a declarative and powerful way to add visual flair to your UI interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs