Build Vue's <Transition>: enter and leave class timing, duration detection, cancellation, and out-in and in-out modes
Problem
Vue's <Transition> does not animate anything itself. It adds and removes CSS classes at exactly the right moments and works out when the browser has finished, so CSS does the animation. Getting those moments right is subtle: the start class must be painted before it is removed, the end must be detected from computed styles, a leave that is interrupted by an enter must be cancelled cleanly, and switching between two elements needs out-in and in-out modes. Build the engine.
const hooks = createTransition({ name: "fade" });
hooks.beforeEnter(el); // class="fade-enter-from fade-enter-active"
container.appendChild(el);
hooks.enter(el);
// two frames later: class="fade-enter-active fade-enter-to"
// after transitionend (or the timeout): class=""Ref. UR-1463 · © UIRound · uiround.com/questions/build-vues-transition-enter-and-leave-class-timing-duration-detection-cancellation-and-out-in-and-in-out-modes
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 5
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Enter is three steps: add
fromandactivebefore insertion, swapfromfortotwo animation frames later (so the browser paints the start state), and removetoandactivewhen the transition ends. Leave is the same withleave-*classes, and removes the element at the end.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.