How to Use Transition in Vue: Simple Guide with Examples
In Vue, you use the
<transition> component to apply animations when elements enter or leave the DOM. Wrap the element you want to animate inside <transition> and define CSS classes or JavaScript hooks for the animation effects.Syntax
The <transition> component wraps the element you want to animate. It automatically applies CSS classes during different phases of the animation:
v-enter-from: Starting state when element entersv-enter-active: Active state during enteringv-enter-to: Ending state when entering finishesv-leave-from: Starting state when element leavesv-leave-active: Active state during leavingv-leave-to: Ending state when leaving finishes
You can customize these class names with the name attribute.
vue
<transition name="fade"> <p v-if="show">Hello Vue Transition!</p> </transition>
Output
The paragraph fades in when shown and fades out when hidden.
Example
This example shows a button toggling a paragraph with a fade effect using CSS transitions.
vue
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="fade">
<p v-if="show">This text will fade in and out.</p>
</transition>
</div>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(false)
</script>
<style>
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-to, .fade-leave-from {
opacity: 1;
}
</style>Output
Clicking the button toggles the paragraph's visibility with a smooth fade animation.
Common Pitfalls
Common mistakes include:
- Not wrapping the element inside
<transition>, so no animation happens. - Forgetting to define CSS classes for the transition phases, resulting in no visible effect.
- Using
v-showinstead ofv-ifinside<transition>without understanding thatv-showonly toggles visibility and does not trigger enter/leave animations.
vue
<!-- Wrong: No transition wrapper --> <p v-if="show">No animation here</p> <!-- Right: Wrapped with transition and CSS classes defined --> <transition name="fade"> <p v-if="show">Animated text</p> </transition>
Quick Reference
Tips for using <transition> in Vue:
- Use
v-ifinside<transition>for enter/leave animations. - Define CSS classes with the pattern
{name}-enter-from,{name}-enter-active, etc. - Use the
nameattribute to customize class prefixes. - For complex animations, use JavaScript hooks instead of CSS.
- Remember
v-showtoggles visibility but does not trigger enter/leave transitions.
Key Takeaways
Wrap elements with
<transition> to animate their entry and exit.Define CSS classes for enter and leave phases to create smooth animations.
Use
v-if inside <transition> for proper transition triggers.Customize animation class names with the
name attribute.Avoid using
v-show for transitions that require enter/leave animations.