0
0
Vueframework~5 mins

Enter and leave transitions in Vue

Choose your learning style9 modes available
Introduction

Enter and leave transitions help make elements appear and disappear smoothly on the page. They make the user experience nicer by adding simple animations.

Showing or hiding a menu when a button is clicked
Displaying a notification that fades in and out
Animating a modal window opening and closing
Making list items appear one by one when loaded
Syntax
Vue
<transition name="fade">
  <div v-if="show">Content</div>
</transition>

The <transition> wrapper adds animation to its child element.

The name attribute sets the CSS classes prefix for the animation.

Examples
This fades the paragraph in and out when visible changes.
Vue
<transition name="fade">
  <p v-if="visible">Hello!</p>
</transition>
This slides the menu in and out using CSS classes starting with slide-.
Vue
<transition name="slide">
  <div v-if="open">Menu content</div>
</transition>
Without a name, Vue uses v- prefixed classes like v-enter-from. Define CSS for them to create animations such as fade.
Vue
<transition>
  <span v-if="show">Hello!</span>
</transition>
Sample Program

This Vue component shows a green box that fades and scales in and out when you click the button. The box is keyboard focusable and announces changes politely for accessibility.

Vue
<template>
  <button @click="toggle">Toggle Box</button>
  <transition name="fade">
    <div v-if="show" class="box" tabindex="0" aria-live="polite">
      I appear and disappear smoothly!
    </div>
  </transition>
</template>

<script setup>
import { ref } from 'vue'
const show = ref(false)
function toggle() {
  show.value = !show.value
}
</script>

<style scoped>
.box {
  width: 200px;
  height: 100px;
  background-color: #4caf50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0.5rem;
  margin-top: 1rem;
  outline: none;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: scale(0.9);
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}
</style>
OutputSuccess
Important Notes

Always wrap the element you want to animate inside a <transition> component.

Use v-if or v-show on the child element to control visibility.

Define CSS classes with the pattern {name}-enter-from, {name}-enter-active, {name}-leave-to, and {name}-leave-active for smooth animations.

Summary

Enter and leave transitions add smooth animations when elements appear or disappear.

Use the <transition> component with a name to apply CSS animations.

Control visibility with v-if or v-show inside the transition wrapper.