Vue Animations

Vue Animations and Transitions

When elements enter or leave the DOM (usually via v-if or v-show), the change is instantaneous.

This sudden appearance or disappearance can feel harsh and unpolished.

Vue provides a built-in <Transition> wrapper component to animate these layout changes beautifully.


The <Transition> Component

To apply a transition, simply wrap your target element inside the <Transition> component.

You must give the transition a name attribute, which acts as the prefix for the CSS classes Vue will generate.

Transition Wrapper:

<button @click="show = !show">Toggle</button>

<Transition name="fade"> <p v-if="show">hello</p> </Transition>


Vue Transition Classes

When an element enters or leaves, Vue automatically adds and removes specific CSS classes.

For a transition named "fade", Vue will look for these CSS classes in your stylesheet:

  1. .fade-enter-from: The starting state for entering. (e.g., opacity: 0)
  2. .fade-enter-active: The active state where you define the transition timing.
  3. .fade-leave-to: The ending state for leaving. (e.g., opacity: 0)
  4. .fade-leave-active: The active state during the leaving phase.

Creating the CSS

Once you have defined your <Transition name="fade">, you just need to write the matching CSS!

Transition CSS Example:

/* The active phases dictate the speed and easing */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

/* The starting and ending points (completely invisible) */ .fade-enter-from, .fade-leave-to { opacity: 0; }


Using External Animation Libraries

Vue's transition system is perfectly compatible with external CSS animation libraries like Animate.css.

Instead of writing custom CSS, you can explicitly map Vue's transition classes to the library's classes.

You do this by passing attributes like enter-active-class="animate__animated animate__bounceIn".


Exercise 1 of 2

?

What component is used to wrap elements that you want to animate when they toggle via v-if?

Exercise 2 of 2

?

If your transition is named "slide", what CSS class defines the timing duration during the entering phase?