JAVASCRIPT

Advanced Custom Transitions with Vue 3 JavaScript Hooks

Create highly customized element transitions in Vue 3 using <Transition> and JavaScript hooks like `beforeEnter`, `enter`, and `leave` for precise animation control.

// src/App.vue
<template>
  <div>
    <button @click="show = !show">Toggle Element</button>
    <Transition
      @before-enter="onBeforeEnter"
      @enter="onEnter"
      @leave="onLeave"
      :css="false" <!-- Important: disables CSS-based transitions -->
    >
      <div v-if="show" class="my-element">Hello, Vue 3!</div>
    </Transition>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import gsap from 'gsap'; // Assuming GSAP is installed for smooth animations

const show = ref(false);

const onBeforeEnter = (el) => {
  gsap.set(el, { opacity: 0, y: -50, scale: 0.8 });
};

const onEnter = (el, done) => {
  gsap.to(el, {
    opacity: 1,
    y: 0,
    scale: 1,
    duration: 0.6,
    ease: 'back.out(1.7)',
    onComplete: done, // Call done() when the animation is complete
  });
};

const onLeave = (el, done) => {
  gsap.to(el, {
    opacity: 0,
    y: 50,
    scale: 0.8,
    duration: 0.4,
    ease: 'power2.in',
    onComplete: done, // Call done() when the animation is complete
  });
};
</script>

<style scoped>
.my-element {
  margin-top: 20px;
  padding: 20px;
  background-color: #42b983;
  color: white;
  border-radius: 8px;
  font-size: 1.5em;
  text-align: center;
}
</style>
How it works: This snippet demonstrates how to leverage Vue 3's `<Transition>` component with JavaScript hooks to create highly custom animations. By setting `:css="false"`, Vue prevents its default CSS transition detection, allowing full control via `before-enter`, `enter`, and `leave` events. These hooks receive the element (`el`) and a `done` callback. Here, the GSAP library is used to define intricate entry and exit animations, ensuring `done()` is called upon completion to signal Vue that the transition is finished and the element can be removed from the DOM (for `onLeave`).

Need help integrating this into your project?

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

Hire DigitalCodeLabs