JAVASCRIPT
Animating Element Entry/Leave with Vue 3 Transitions
Master Vue 3's built-in <Transition> and <TransitionGroup> components to create smooth animations for elements entering, leaving, or reordering within your web applications.
// App.vue
<template>
<button @click="show = !show">Toggle Element</button>
<Transition name="fade">
<p v-if="show">Hello Vue!</p>
</Transition>
<hr>
<button @click="addItem">Add Item</button>
<button @click="shuffleItems">Shuffle Items</button>
<TransitionGroup name="list" tag="ul">
<li v-for="item in items" :key="item.id">
{{ item.text }}
<button @click="removeItem(item.id)">X</button>
</li>
</TransitionGroup>
</template>
<script setup>
import { ref } from 'vue';
import { shuffle } from 'lodash'; // Using lodash for shuffling for demo
const show = ref(true);
let nextId = 4;
const items = ref([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
]);
const addItem = () => {
const newItem = { id: nextId++, text: `Item ${nextId - 1}` };
const randomIndex = Math.floor(Math.random() * (items.value.length + 1));
items.value.splice(randomIndex, 0, newItem);
};
const removeItem = (id) => {
items.value = items.value.filter(item => item.id !== id);
};
const shuffleItems = () => {
items.value = shuffle(items.value); // Requires 'lodash' or similar utility
};
</script>
<style>
/* Transition for a single element */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
/* Transition group for lists */
.list-move, /* apply transition to moving elements */
.list-enter-active,
.list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* ensure leaving items are taken out of layout flow so that moving
animations can be calculated correctly. */
.list-leave-active {
position: absolute;
}
ul { list-style: none; padding: 0; }
li {
margin-top: 10px;
padding: 10px;
background-color: #f0f0f0;
border-left: 5px solid #42b983;
display: flex;
justify-content: space-between;
align-items: center;
}
li button { background-color: #ff4d4d; color: white; border: none; padding: 5px 8px; cursor: pointer; }
</style>
How it works: Vue's `<Transition>` component facilitates animating elements that are entering or leaving the DOM. It applies specific CSS classes at different stages of the transition, allowing you to define CSS transitions or animations. `<TransitionGroup>` extends this for lists, providing smooth animations for item insertion, removal, and reordering. Note that for `TransitionGroup`, it's important to set `position: absolute` on `.list-leave-active` to ensure moving items calculate their new positions correctly.