Understanding and Implementing Vue's nextTick Mechanism
This article explains the inner workings of Vue's nextTick function, detailing its callback queue, flushing logic, timer selection across environments, Promise‑based return, and provides a step‑by‑step JavaScript implementation with test cases and the full Vue source code.
The article begins by describing the interview question about Vue's nextTick implementation and outlines the three core components used before calling this.$nextTick(cb) : a callbacks array to store pending callbacks, a flushCallbacks function that executes and clears the array, and a timerFunc that schedules flushCallbacks in the task queue.
When nextTick(cb) is invoked, the callback is pushed into callbacks . The function then checks whether this is the first call in the current event loop; if so, it runs timerFunc to enqueue flushCallbacks . If no callback is supplied, a Promise is returned, allowing await this.$nextTick() usage.
The core implementation is presented in a concise JavaScript snippet that defines callbacks , pending , flushCallbacks , and nextTick . The snippet shows how the pending flag prevents duplicate scheduling and how Promise.resolve().then(flushCallbacks) is used when the environment supports native promises.
Two test examples demonstrate the behavior: one with a direct callback that logs the updated message, and another using await nextTick() to show the promise‑based flow.
The article then explains how Vue selects the most efficient asynchronous API based on browser capabilities: Promise → MutationObserver → setImmediate → setTimeout . Each fallback is described, including the creation of a dummy text node for the MutationObserver approach and the handling of iOS‑specific bugs.
A complete Vue source version of nextTick is provided, adding native‑code checks, error handling via handleError , and context binding. The full code block shows the final decision logic for timerFunc and the extended nextTick signature that supports optional context and promise resolution.
In the conclusion, the author emphasizes that understanding these three steps—callback storage, flushing, and environment‑aware scheduling—gives developers the ability to explain nextTick confidently in interviews and to apply the pattern in real projects.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.