JAVASCRIPT

Adding Enter/Leave Transitions to Vue 3 Elements

Implement smooth enter and leave animations for conditionally rendered elements in Vue 3 using the built-in `<Transition>` component and CSS transitions.

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

    <!-- Basic Transition -->
    <Transition name="fade">
      <p v-if="show" class="message-box">Hello, Vue 3 Transitions!</p>
    </Transition>

    <button @click="showAnother = !showAnother">Toggle Box</button>

    <!-- Transition with custom classes -->
    <Transition
      name="slide-fade"
      enter-active-class="animate__animated animate__fadeInLeft"
      leave-active-class="animate__animated animate__fadeOutRight"
      mode="out-in"
    >
      <div v-if="showAnother" key="box" class="animated-box">This is an animated box!</div>
      <div v-else key="placeholder" class="placeholder-box">Click to show box</div>
    </Transition>

  </div>
</template>

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

const show = ref(true);
const showAnother = ref(false);
</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 (using custom classes for animate.css integration example) */
/* To use animate.css, you'd need to install it: npm install animate.css */
/* @import 'animate.css'; */
.message-box {
  background-color: #e0f7fa;
  padding: 15px;
  border-left: 5px solid #00bcd4;
  margin-top: 20px;
}

.animated-box {
  background-color: #ffe0b2;
  padding: 20px;
  border-left: 5px solid #ff9800;
  margin-top: 20px;
  width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.placeholder-box {
  background-color: #f5f5f5;
  padding: 20px;
  border: 1px dashed #ccc;
  margin-top: 20px;
  width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
}
</style>
How it works: This snippet demonstrates how to add enter and leave transitions to elements in Vue 3 using the `<Transition>` component. By wrapping a conditionally rendered element with `<Transition>` and defining CSS classes for `name="fade"` or using `enter-active-class`/`leave-active-class` with external animation libraries like Animate.css, you can create smooth visual effects when elements appear or disappear from the DOM. The `mode="out-in"` property ensures that the leaving element finishes its transition before the entering element starts, preventing visual overlap.

Need help integrating this into your project?

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

Hire DigitalCodeLabs