JAVASCRIPT

Animating List Items with Vue 3 TransitionGroup

Learn to effortlessly animate the insertion, removal, and reordering of list items in Vue 3 using the powerful `<TransitionGroup>` component and CSS.

// App.vue
<template>
  <div>
    <h1>My Todo List</h1>
    <input v-model="newItem" @keyup.enter="addItem" placeholder="Add new todo" />
    <TransitionGroup name="todo-list" tag="ul">
      <li v-for="item in items" :key="item.id">
        {{ item.text }}
        <button @click="removeItem(item.id)">X</button>
      </li>
    </TransitionGroup>
  </div>
</template>

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

let id = 0;
const newItem = ref('');
const items = ref([
  { id: id++, text: 'Learn Vue 3' },
  { id: id++, text: 'Build amazing things' },
]);

function addItem() {
  if (newItem.value.trim()) {
    items.value.unshift({ id: id++, text: newItem.value });
    newItem.value = '';
  }
}

function removeItem(itemId) {
  items.value = items.value.filter((item) => item.id !== itemId);
}
</script>

<style>
/* CSS for transitions */
.todo-list-enter-active,
.todo-list-leave-active {
  transition: all 0.5s ease;
}
.todo-list-enter-from,
.todo-list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* ensure leaving items animate out of view without re-shuffling */
.todo-list-leave-active {
  position: absolute;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `<TransitionGroup>` component to animate list items. By wrapping a `v-for` list with `<TransitionGroup>`, you can apply CSS transitions to items as they are added, removed, or reordered. The `name` prop links the component to specific CSS classes (e.g., `.todo-list-enter-active`), which define the animation. The `tag` prop allows you to specify the root element rendered by the transition group (e.g., `<ul>`).

Need help integrating this into your project?

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

Hire DigitalCodeLabs