In https://v2.vuejs.org/v2/guide/reactivity.html#Async-Update-Queue, the doc tells us that if you want to do something (e.g. get the new width & height of an element) after render is completed, you should do it in callback of Vue.nextTick(callback). But at few times I found it didn't work (I don't know if others found it not work at times too) and must resort to setTimeout to fix it.
I doubt how nextTick can ensure that render is completed totally. I read the source code and find that it may use Promise.then, setImmediate or setTimeout(cb, 0) to run your code at the nextTick. I think dom rendering can happen any time between ticks of event loop. So the all the internal methods used by nextTick can't ensure that the new rendering work is done.
[Note] I am not to discuss whether it is a good way to call nextTick to resolve
some problem, it is another question. My point is why it can do what it provided(dom render is completed).
Can someone give me an explanation about it? Thanks.
nextTick does not guarantee the DOM render is completed, it just guarantee that the DOM structure is updated.
You can access the updated DOM using something like this.$refs.p.innerHTML inside nextTick's callback.
But you may not see that content on the screen yet.
nextTick put your callback inside a microtask queue, after all the microtasks is completed then the browser will have a chance to render the new content.
If you want to wait for the content to display on the screen, you can use setImmediate (IE only) or setTimeout(fn, 0) which has lower priority than the render task so it will execute after the new content is displayed.
See this answer for example fiddle:
https://forum.vuejs.org/t/does-nexttick-work-weirdly/42918/7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With