JAVASCRIPT

Animating Element Transitions with Vue 3's <Transition> Component

Learn to apply smooth entry and exit animations to elements and components using Vue 3's powerful <Transition> component and CSS transitions.

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

    <button @click="addItem">Add Item</button>
    <button @click="removeItem">Remove Item</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';

const show = ref(true);

const items = ref(['Apple', 'Banana', 'Cherry']);
let nextItemId = 4;

const addItem = () => {
  const newItem = `Item ${nextItemId++}`;
  const randomIndex = Math.floor(Math.random() * (items.value.length + 1));
  items.value.splice(randomIndex, 0, newItem);
};

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

<style scoped>
/* CSS for <Transition name="fade"> */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* CSS for <TransitionGroup name="list"> */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
.list-move {
  transition: transform 0.5s ease;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's built-in `<Transition>` and `<TransitionGroup>` components to add smooth entry, exit, and reordering animations. For single elements (like a paragraph), `<Transition>` paired with CSS classes (`.fade-enter-from`, `.fade-leave-to`, etc.) creates a fade effect. For lists rendered with `v-for`, `<TransitionGroup>` allows for individual item animations and smooth transitions when items are added, removed, or reordered, enhancing the user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs