JAVASCRIPT
Vue 3 Transitions for Element Entry/Exit
Implement smooth entry and exit animations for elements in Vue 3 using the <Transition> component and CSS classes, perfect for toggling visibility of content like warnings or modals.
<template>
<div>
<button @click="show = !show">Toggle Message</button>
<Transition name="slide-fade">
<p v-if="show" class="message">Hello from Vue 3!</p>
</Transition>
<h2>Transition Group Example</h2>
<button @click="addNumber">Add Number</button>
<button @click="removeNumber">Remove Number</button>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item" class="list-item">
{{ item }}
</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref } from 'vue';
const show = ref(true);
const items = ref([1, 2, 3, 4, 5]);
let nextNum = 6;
function addNumber() {
const randIndex = Math.floor(Math.random() * items.value.length);
items.value.splice(randIndex, 0, nextNum++);
}
function removeNumber() {
if (items.value.length > 0) {
const randIndex = Math.floor(Math.random() * items.value.length);
items.value.splice(randIndex, 1);
}
}
</script>
<style>
/* Basic element transition */
.slide-fade-enter-active {
transition: all 0.3s ease-out;
}
.slide-fade-leave-active {
transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter-from, .slide-fade-leave-to {
transform: translateX(20px);
opacity: 0;
}
/* List transition */
.list-item {
transition: all 0.8s ease;
display: inline-block; /* For list items */
margin-right: 10px;
}
.list-enter-from, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
/* ensure leaving items are taken out of layout flow so that moving
animations can be calculated correctly. */
.list-leave-active {
position: absolute;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<Transition>` and `<TransitionGroup>` components to add animations for element entry/exit and list item changes. The `<Transition>` component wraps a single element (e.g., a paragraph with `v-if`) and applies CSS transition classes (`.slide-fade-enter-from`, `.slide-fade-enter-active`, etc.) during its appearance or disappearance. `<TransitionGroup>` is used for lists rendered with `v-for`, allowing individual items to animate when added, removed, or reordered. CSS rules define the visual transitions for these states.