3
votes

From the Vue.js documentation, the $nextTick is explained as:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

Great! So the second statement says to use it immediately after some data has changed and I know setTimeout with 0 is also called immediately. I created this little sandbox to understand the two but still, I don't seem to get the difference between the two approaches?

Any explanation on their difference will be much appreciated.

1

1 Answers

4
votes

The difference is that $nextTick knows when the DOM has been updated and triggers accordingly whereas setTimeout is idempotent and triggers after the specified millisecond delay. See this excellent answer on the latter but the gist is that the delay is a minimum, not an exact timeout.


Say for example, you have some state that triggers the inclusion of an <input> element

<input ref="textBox" v-if="showTextBox">

Using $nextTick, you can safely execute the following because the callback will only be executed once the DOM has updated to include the <input>

this.showTextBox = true
this.$nextTick(() => {
  this.$refs.textBox.focus()
})

Now consider the (theoretical) situation where it takes an arbitrary amount of time to add that <input> to the DOM that is longer than it takes to trigger the setTimeout callback

this.showTextBox = true
setTimeout(() => {
  // will throw "Uncaught TypeError: Cannot read property 'focus' of undefined"
  this.$refs.textBox.focus() 
}, 0)