What is nextTick in Vue?
Quick Answer
Vue batches DOM updates — when you change reactive state, the DOM isn't updated synchronously. await nextTick() (or nextTick(cb)) waits until Vue has flushed those updates, so you can safely read the updated DOM — measure an element, focus an input that was just v-if'd in, scroll to new content.
Vue doesn't update the DOM the instant you change data — it batches all the changes and applies them together on the next tick. So if I set a flag that adds an input with v-if and then immediately try to focus it via a ref, the element isn't there yet. await nextTick() pauses until Vue has flushed the DOM update, and then the ref is valid and I can focus it or measure it. It's for any “change data, then touch the resulting DOM” situation.
- Without it:
this.showInput = true; this.$refs.input.focus()— the ref doesn't exist yet because the DOM hasn't rendered. - With it:
this.showInput = true; await nextTick(); this.$refs.input.focus(). - Vue schedules the flush as a microtask, so
nextTickresolves very quickly.