在 vuejs 中使用 vue $nextTick 与 setTimeout 0 有什么区别

What is the difference between using vue $nextTick vs setTimeout 0 in vuejs

Vue.js documentation开始,$nextTick解释为:

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.

太棒了!所以第二条语句说在一些数据发生变化后立即使用它,我知道 setTimeout with 0 也会被立即调用。我创建这个 little sandbox 是为了理解这两种方法,但我似乎还是没有弄清楚这两种方法之间的区别?

任何关于它们差异的解释将不胜感激。

区别在于$nextTick知道DOM何时更新并相应地触发而setTimeout是幂等的并且在之后触发指定的毫秒延迟。请参阅后者的 ,但要点是延迟是最小值,而不是确切的超时。


例如,您有一些状态会触发包含 <input> 元素

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

使用 $nextTick,您可以安全地执行以下操作,因为回调只会在 DOM 更新为包含 <input>

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

现在考虑这样一种(理论上的)情况,在这种情况下,将 <input> 添加到 DOM 所花费的时间比触发 setTimeout 回调所花费的时间要长

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