JAVASCRIPT

Animating Element Appearances with Vue 3 Transitions

Implement smooth entry/exit animations for elements and components using Vue 3's built-in `<Transition>` component, enhancing user experience with CSS transitions.

// App.vue
<template>
  <div>
    <button @click="show = !show">Toggle Box</button>

    <Transition name="fade">
      <div v-if="show" class="box">
        Hello, Vue Transitions!
      </div>
    </Transition>

    <Transition name="slide-fade">
      <p v-if="show">This text slides and fades.</p>
    </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;
}

.box {
  width: 200px;
  height: 100px;
  background-color: lightblue;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  border-radius: 5px;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<Transition>` component to add entry and exit animations to elements. When an element inside a `<Transition>` is conditionally rendered (e.g., with `v-if` or `v-show`), Vue automatically applies transition classes. The `name` prop (e.g., 'fade', 'slide-fade') prefixes these classes (e.g., `.fade-enter-from`, `.fade-leave-to`, `.fade-enter-active`). By defining CSS transitions and transformations for these classes, you can create smooth visual effects. This approach integrates seamlessly with CSS, offering powerful and flexible animation capabilities without complex JavaScript.

Need help integrating this into your project?

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

Hire DigitalCodeLabs