Vue performs DOM updates asynchronously! But what does mean?
I will begin by explain you what is going on if we don't use an async update queue.
Normal case
Imagine that we have an array and we show it into the DOM, each time we push a new item, we will render the DOM.
It's not really dramatic if we only add some items. But imagine if we decide to add 1000 items in this array at the same moment, we will render our DOM 1000 times! Your DOM will explode π€―.
We don't really need to update the DOM 1000 times, we only need one time, and we should only update it when we finish to add all items!
Async update queue
Vue performs DOM updates asynchronously. Whenever a data change is observed (in our case, adding item into our array), it will NOT directly update the DOM, it will add all change into a queue (buffer).
It wait a few time (time needed to add all items to our array) and after this it will update the DOM. So we add 1000 items but we will update the DOM only ONE TIME!
This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations.
The moment when the queue will update the DOM is called a tick
!
In general we don't need to careful about this, except if we need to do some action depending on the DOM State. But it's not really recommended to base your action on DOM state, we recommend you to use component state instead of DOM state.
Example
<div id="example">{{ message }}</div>
const vm = new Vue({
el: '#example',
data: {
message: '123'
}
})
vm.message = 'new message' // change data, but vue will not re-render immediately !
vm.$el.textContent === 'new message' // false since the update is in the Queue, and not updated for the moment in the DOM
// NextTick is the moment where the Queue update all changed !
Vue.nextTick(function () {
// The DOM is update with the new change!
vm.$el.textContent === 'new message' // true
})
You can also use await this.$nextTick()
instead of callback!
In some test case
you should need to check if your value is updated in the DOM, in this case you will need to use nextTick
before checking this update!
Conclusion or TLDR
Async render queue allow vue to update the DOM only after a moment called tick
, it permit to avoid unneeded updated to the DOM.
When you need to check a value in the DOM (not recommended), you need to wait the nextTick
before checking the value in the DOM, otherwise the value will be not updated at this moment!
I hope you like this reading!
π You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and MP me π
Or get it HERE
π MY NEWSLETTER
βοΈ You can SUPPORT MY WORKS π
πββοΈ You can follow me on π
π Twitter : https://twitter.com/code__oz
π¨βπ» Github: https://github.com/Code-Oz
And you can mark π this article!
Top comments (0)