JAVASCRIPT

Vue 3 Custom JavaScript Transition Hooks for Complex Animations

Implement highly customized entrance and exit animations in Vue 3 using JavaScript transition hooks, offering precise control over element transitions beyond CSS-only methods.

// <template>
//   <div>
//     <button @click="show = !show">Toggle Element</button>
//     <Transition
//       @before-enter="onBeforeEnter"
//       @enter="onEnter"
//       @leave="onLeave"
//       :css="false"
//     >
//       <div v-if="show" class="my-animated-element">
//         I'm animated with JavaScript!
//       </div>
//     </Transition>
//   </div>
// </template>

// <script setup>
// import { ref } from 'vue';
// import gsap from 'gsap'; // Assuming GSAP is installed: npm install gsap

// const show = ref(false);

// function onBeforeEnter(el) {
//   gsap.set(el, {
//     opacity: 0,
//     x: -100,
//     scale: 0.8
//   });
// }

// function onEnter(el, done) {
//   gsap.to(el, {
//     opacity: 1,
//     x: 0,
//     scale: 1,
//     duration: 0.8,
//     ease: "power2.out",
//     onComplete: done // Call done when the animation is complete
//   });
// }

// function onLeave(el, done) {
//   gsap.to(el, {
//     opacity: 0,
//     x: 100,
//     scale: 0.8,
//     duration: 0.5,
//     ease: "power2.in",
//     onComplete: done // Call done when the animation is complete
//   });
// }
// </script>

// <style>
// .my-animated-element {
//   padding: 20px;
//   background-color: #42b983;
//   color: white;
//   border-radius: 8px;
//   margin-top: 20px;
//   font-size: 1.2em;
//   text-align: center;
// }
// </style>
How it works: This snippet demonstrates how to leverage Vue 3's `<Transition>` component with custom JavaScript hooks for fine-grained control over element animations, bypassing CSS transitions entirely. By setting `:css="false"` on the `Transition` component, Vue will look for `before-enter`, `enter`, `before-leave`, and `leave` event listeners. Here, the GSAP library is used within these hooks to define complex `opacity`, `position`, and `scale` animations. The `done` callback must be called at the end of the `enter` and `leave` hooks to signal Vue that the animation is complete, allowing the element to be inserted or removed from the DOM. This method is ideal for animations requiring advanced timing, sequencing, or physics-based effects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs