JAVASCRIPT

Animated List Transitions with Vue 3's TransitionGroup

Implement smooth, animated transitions for lists, adding, removing, or reordering elements using Vue 3's <TransitionGroup> component for enhanced user experience.

<script setup>
import { ref } from 'vue'

const items = ref(['Vue', 'React', 'Angular'])
const newItem = ref('')

function addItem() {
  if (newItem.value.trim() !== '') {
    items.value.push(newItem.value.trim())
    newItem.value = ''
  }
}

function removeItem(itemToRemove) {
  items.value = items.value.filter(item => item !== itemToRemove)
}

function shuffle() {
  items.value.sort(() => Math.random() - 0.5)
}
</script>

<template>
  <div>
    <input v-model="newItem" @keyup.enter="addItem" placeholder="Add a new framework" />
    <button @click="addItem">Add Item</button>
    <button @click="shuffle">Shuffle</button>

    <TransitionGroup name="list" tag="ul">
      <li v-for="item in items" :key="item">
        {{ item }}
        <button @click="removeItem(item)">x</button>
      </li>
    </TransitionGroup>
  </div>
</template>

<style>
.list-move,
.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;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<TransitionGroup>` component to animate the insertion, removal, and reordering of elements in a list. The `name="list"` prop links the component to the CSS transition classes (e.g., `.list-enter-from`, `.list-leave-to`, `.list-move`). Crucially, each item inside `<TransitionGroup>` must have a unique `:key` attribute for Vue to track its identity and apply animations correctly. The `.list-move` class is automatically applied during reordering, and `.list-leave-active { position: absolute; }` helps prevent layout jumps when items are removed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs