Vue.js provides a built-in <transition> component to apply trensition effects when elements are inserted, updated, or removed from the DOM. These transitions can be implemented using CSS classes, CSS animations, or JavaScript hooks.
CSS Transitions
For basic CSS transitions, Vue automatically toggles specific classes during different phases of the transition lifecycle. The structure involves wrapping the target element with a <transition> tag and defining corresponding CSS classes:
<!-- Template -->
<transition name="fade">
<p v-if="isVisible">Hello!</p>
</transition>
<!-- Styles -->
.fade-enter-active {
transition: opacity 0.3s ease;
}
.fade-leave-active {
transition: opacity 0.8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
The class naming convention uses the transition name as a prefix followed by one of these suffixes:
-enter-from: Starting state for enter-enter-active: Active state during enter-leave-from: Starting state for leave-leave-active: Active state during leave-leave-to: Ending state for leave
During the transition, Vue dynamically adds and removes these classes to trigger the defined CSS transitions.
CSS Animations
CSS animations use @keyframes and are applied similarly, but the animation is declared within the active classes:
<transition name="bounce">
<div v-if="show" class="box"></div>
</transition>
.bounce-enter-active {
animation: fadeInScale 0.5s;
}
.bounce-leave-active {
animation: fadeOutScale 0.5s;
}
@keyframes fadeInScale {
0% { transform: scale(0); opacity: 0; }
100% { transform: scale(1); opacity: 1; }
}
@keyframes fadeOutScale {
0% { transform: scale(1); opacity: 1; }
100% { transform: scale(0); opacity: 0; }
}
Using Third-Party CSS Libraries
Libraries like Animate.css can be integrated by specifying custom clas names via transition attributes:
<transition
enter-active-class="animated fadeInUp"
leave-active-class="animated fadeOutDown"
>
<p v-if="isVisible">Message</p>
</transition>
Note that animated is required when using Animate.css.
Transition Modes
When transitioning between elements (e.g., toggling between two components), Vue supports two transition modes:
out-in: Current element transitions out first, then the new one transitions in.in-out: New element transitions in first, then the current one transitions out.
To ensure proper behavior, always assign unique key attributes to each element:
<transition name="slide" mode="out-in">
<component :is="currentView" :key="currentView"></component>
</transition>