JAVASCRIPT

Vue 3 Element Enter/Leave Transitions

Animate elements entering and leaving the DOM in Vue 3 using the built-in `<Transition>` component, providing smooth and engaging user interface changes with CSS transitions.

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

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

<template>
  <div>
    <h1>Vue 3 Transition Example</h1>
    <button @click="showMessage = !showMessage">Toggle Message</button>

    <Transition name="fade">
      <p v-if="showMessage">Hello Vue 3 Animations!</p>
    </Transition>

    <Transition name="slide-fade">
      <div v-if="showMessage" class="box">
        This box will slide and fade.
      </div>
    </Transition>
  </div>
</template>

<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 {
  margin-top: 20px;
  padding: 15px;
  background-color: #e0f2f7;
  border: 1px solid #a7d9ed;
  border-radius: 5px;
}
</style>
How it works: This snippet demonstrates how to apply enter and leave transitions to elements in Vue 3 using the `<Transition>` component. By wrapping a conditionally rendered element with `<Transition>` and giving it a `name` prop (e.g., `fade` or `slide-fade`), Vue automatically applies CSS classes during the enter and leave phases. Corresponding CSS rules target these classes (`.fade-enter-from`, `.fade-enter-active`, `.fade-leave-to`, etc.) to define the animation properties, enabling smooth visual effects when elements are added to or removed from the DOM.

Need help integrating this into your project?

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

Hire DigitalCodeLabs