JAVASCRIPT

Animating Element Appearance/Disappearance with Vue 3 Transitions

Utilize Vue 3's built-in `<Transition>` component to gracefully animate the entry and exit of single elements or components with CSS transitions.

<template>
  <div>
    <button @click="show = !show">Toggle Element</button>
    <Transition name="fade">
      <p v-if="show">Hello, Vue 3 Transitions!</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.id">{{ item.text }}</li>
    </TransitionGroup>
  </div>
</template>

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

const show = ref(true);
const items = ref([{ id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }]);
let nextId = 3;

const addItem = () => {
  items.value.push({ id: nextId++, text: `Item ${nextId - 1}` });
};

const removeItem = () => {
  if (items.value.length > 0) {
    items.value.pop();
  }
};
</script>

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

/* 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-leave-active {
  position: absolute; /* Ensures elements don't jump when one is removed */
}
.list-move {
  transition: transform 0.5s ease;
}
</style>
How it works: Vue's built-in `<Transition>` and `<TransitionGroup>` components allow you to apply CSS transitions and animations when elements are inserted into, updated in, or removed from the DOM. `<Transition>` handles single elements, while `<TransitionGroup>` handles lists, adding class names during different stages of the transition (e.g., `fade-enter-from`, `fade-enter-active`, `fade-leave-to`). You then define CSS rules for these classes to create desired visual effects like fading, sliding, or scaling. For `<TransitionGroup>`, `position: absolute` on `*-leave-active` and `*-move` classes are crucial for smooth list item transitions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs