The Transition component helps you add smooth animations when elements appear, disappear, or change on the page. It makes your app feel lively and polished.
0
0
Transition component basics in Vue
Introduction
When showing or hiding a menu or popup with a fade effect.
When switching between different views or pages with a slide animation.
When adding or removing items in a list with a smooth transition.
When you want to highlight changes in content with animation.
When you want to improve user experience by avoiding sudden content jumps.
Syntax
Vue
<Transition name="fade"> <div v-if="show">Content here</div> </Transition>
The component wraps the element you want to animate.
The 'name' attribute sets the base class for CSS animations.
Examples
This example fades a paragraph in and out when 'visible' changes.
Vue
<Transition name="fade"> <p v-if="visible">Hello!</p> </Transition>
This example slides a 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 default transition classes for animation.
Vue
<Transition>
<button v-if="showButton">Click me</button>
</Transition>Sample Program
This component shows a button that toggles a message. The message fades in and out smoothly using the Transition component and CSS classes.
Vue
<template>
<div>
<button @click="toggle">Toggle Message</button>
<Transition name="fade">
<p v-if="showMessage" class="message">Hello, Vue!</p>
</Transition>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showMessage = ref(false)
function toggle() {
showMessage.value = !showMessage.value
}
</script>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
.message {
padding: 1rem;
background-color: #def;
border-radius: 0.5rem;
margin-top: 1rem;
}
</style>OutputSuccess
Important Notes
Always pair v-if or v-show with
Use CSS classes with the naming pattern {name}-enter-active, {name}-enter-from, etc., to control animations.
Transitions improve user experience by making changes feel natural and less abrupt.
Summary
The Transition component wraps elements to animate their appearance and disappearance.
Use the 'name' attribute to define CSS class prefixes for animations.
Combine with v-if or v-show to control when elements show or hide with animation.