JAVASCRIPT

Smooth UI Transitions with Vue 3's Transition Component

Master Vue 3's built-in `<Transition>` and `<TransitionGroup>` components to add elegant entry, exit, and update animations to elements and lists, enhancing user experience.

<template>
  <div>
    <button @click="show = !show">Toggle Paragraph</button>
    <Transition name="fade">
      <p v-if="show">Hello, Vue 3 Animations!</p>
    </Transition>

    <hr>

    <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">
        {{ item }}
      </li>
    </TransitionGroup>
  </div>
</template>

<script setup>
import { ref } from 'vue';
// Transition and TransitionGroup are globally available, no explicit import needed

const show = ref(true);
const items = ref([1, 2, 3, 4, 5]);
let nextNum = 6;

function addNumber() {
  const i = Math.floor(Math.random() * items.value.length);
  items.value.splice(i, 0, nextNum++);
}

function removeNumber() {
  if (items.value.length === 0) return;
  const i = Math.floor(Math.random() * items.value.length);
  items.value.splice(i, 1);
}
</script>

<style>
/* CSS for single element transition */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* CSS for list transition */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* Ensure leaving elements don't affect layout during transition */
.list-leave-active {
  position: absolute; /* This helps prevent layout shifts */
}

/* Optional: move transition for shuffling items */
.list-move {
  transition: transform 0.5s ease;
}
</style>
How it works: The `<Transition>` component is a powerful built-in tool in Vue 3 for adding animations when elements or components are inserted, updated, or removed from the DOM. This snippet demonstrates a simple `fade` transition for a single element and a `list` transition for a list of items using `<TransitionGroup>`, showing how CSS classes like `*-enter-active`, `*-enter-from`, `*-leave-active`, and `*-leave-to` are used to define the animation states. The `list-move` class is also shown for animating position changes in `<TransitionGroup>`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs