Implementing Vue.js Transitions with JavaScript Hooks

While CSS transitions and animatinos cover most use cases in Vue.js, JavaScript hooks provide granular control over the transition lifecycle. By attaching methods to speicfic transition events, you can perform complex animations, integrate third-party libraries like Velocity.js, or manipulate the DOM directly during the transition process.

Understanding Lifecycle Hooks

Think of transition hooks as event listeners triggered at precise stages of an element's appearance or disappearance. Vue provides eight hooks across two main phases: entering and leaving.

Enter Hooks

  • before-enter: Triggered before the element is inserted into the DOM. This is the ideal place to set initial styles, such as opacity: 0.
  • enter: The core of the transition. When using JavaScript, you must manually trigger the done() callback to signal that the animation has finished.
  • after-enter: Called once the enter transition is complete.
  • enter-cancelled: Executed if the enter transition is aborted before completion.

Leave Hooks

  • before-leave: Fired immediately when the leave transition starts.
  • leave: The core leave animation logic. Similar to the enter hook, you must call the done() callback.
  • after-leave: Called after the element has been removed from the DOM.
  • leave-cancelled: Executed if the leave transition is aborted.

Example Implementatoin

To use JavaScript hooks, bind them directly to the <transition> component via v-on attributes. Each function receives the transitioning DOM element (el) as its primary argument.

<transition
 @before-enter="prepareElement"
 @enter="animateIn"
 @leave="animateOut"
 :css="false"
>
 <div v-if="isVisible">Content goes here</div>
</transition>

<script>
export default {
 methods: {
   prepareElement(el) {
     el.style.opacity = 0;
   },
   animateIn(el, done) {
     // Use GSAP, Velocity.js, or native Web Animations API
     el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 500 })
       .onfinish = done;
   },
   animateOut(el, done) {
     el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 500 })
       .onfinish = done;
   }
 }
}
</script>

Setting :css="false" is a best practice when using JavaScript hooks. It informs Vue that the transition is handled entirely by JavaScript, which prevents Vue from attempting to detect or apply CSS transition/animation classes, thereby improving performance and avoiding style conflicts.

Tags: Vue.js javascript web-animations frontend-development

Posted on Fri, 22 May 2026 19:12:55 +0000 by luv2sd