JAVASCRIPT

Vue 3 Component Transitions with CSS

Enhance user interfaces with smooth entry/exit transitions for elements or components in Vue 3 using the built-in `<Transition>` component and CSS.

// src/components/FadeTransition.vue
<script setup>
import { ref } from 'vue';

const showElement = ref(true);

const toggleElement = () => {
  showElement.value = !showElement.value;
};
</script>

<template>
  <button @click="toggleElement">Toggle Element</button>
  <!-- Wrap the element to transition with <Transition> -->
  <Transition name="fade">
    <p v-if="showElement" class="my-text">Hello, I'm fading!</p>
  </Transition>
</template>

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

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

/* Optional: for demonstration of the element itself */
.my-text {
  padding: 10px;
  background-color: #e0f7fa;
  border: 1px solid #00bcd4;
  margin-top: 20px;
}
</style>
How it works: Vue's `<Transition>` component is a powerful feature for applying CSS transitions and animations when elements or components are inserted, updated, or removed from the DOM. By wrapping an element with `<Transition>` and providing a `name` prop, Vue automatically applies specific CSS classes (e.g., `fade-enter-from`, `fade-enter-active`, `fade-leave-to`) during the transition phases. You then define the corresponding CSS rules for these classes to create smooth visual effects like fading, sliding, or scaling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs