This article will briefly compare $nextTick and setTimeout to see the differences between them.
A front-end developer (Xiao Zhi) walked into a Vue bar. Ash ordered his favorite cocktail: Nuxt. The bartender is hard at work making it. Then he started chattering to himself.
Xiao Zhi told how he discovered $nextTick
under the instance method of Vue 3 and was surprised. Xiaozhi has been using Vue for some time, and he has become accustomed to writing $watch
and $emit
as instance methods. So, what is $nextTick used for? The Vue documentation says that it "[defers] a callback that is executed after the next DOM update cycle".
But Xiaozhi didn’t believe it.
He went on to tell how he tried to do this:
this.loadingAnimation = true this.startVeryLongCalculation() this.completeVeryLongCalculation() this.loadingAnimation = false
It worked. Why?
nextTick
Accepts a callback function that is delayed until the next DOM update cycle. This is just Vue's way of saying, "Hey, if you want to execute a function after the DOM has updated (which rarely happens), I want you to use nextTick
instead of setTimeout
".
Vue.nextTick(() => {}) // syntax
The setTimeout
and nextTick
parameters will be discussed soon. We use this example to visualize the behavior of nextTick
:
<template> <div> {{ currentTime }} </div> </template> <script> export default { name: 'getCurrentTime', data() { return { currentTime: '' } }, mounted() { this.currentTime = 3; this.$nextTick(() => { let date = new Date() this.currentTime = date.getFullYear() }); } } </script>
Run this code snippet on J computer. It will show 2021
year. It's not that you won't get the same result if you remove nextTick
. However, you should understand that Vue will modify the DOM based on the content of the data.
In the above code snippet, Vue updates the DOM to 3
, then calls the callback, updates the DOM to 2021
, and finally hands control to the browser , the browser will display 2021
.
So far, we have looked at nextTick inserting a callback function in the callback queue and executing the function at the appropriate time.
You may be interested in this. The callback in nextTick
is used as a microtask in the event loop. The source code
of nextTick clearly states that "nextTick
behavior utilizes a microtask queue and can be passed through local Promise.then
or MutationObserver
to access."
Another way to execute a function after a DOM update is to use JavaScript's setTimeout()
function.
We will replace the above code with setTimeout
nextTick
:
<template> <div> {{ currentTime }} </div> </template> <script> export default { name: 'getCurrentTime', data() { return { currentTime: '' } }, mounted() { this.currentTime = 3; setTimeout(() => { let date = new Date() this.currentTime = date.getFullYear() }, 0); } } </script>
to run this code snippet. First see 3
then 2021
. It happens quickly, so you need to refresh your browser if you don't see this behavior.
In the above code snippet, Vue updates the DOM to 3
and provides browser control. Then the browser displays 3
, calls the callback function, updates the DOM to 2021
, and finally hands control to the browser, and now the browser displays 2021
. The implementation of
nextTick
is used on browsers that do not support Promise
and MutationObserver
(IE 6-10 and Opera Mini browsers). setTimeout
is used as a fallback method, which prefers setImmediate
for browsers that do not support Promise
and MutationObserver
(IE 10).
setTimeout
Uncaught (in promise) DOMException
were encountered. Remember, Vue updates the DOM asynchronouslyFinally, here is an example:
<div id="app"> <div ref="listScroll" class="scrolledList"> <ul ref="scrolledHeight"> <li v-for="month in months"> {{month}} </li> </ul> </div> <input type="text" placeholder="Add Month" v-model="month"> <button @click="addMessage" @keyup.enter="addMessage"> Add Month</button> </div> <script src="https://unpkg.com/vue@next"> Vue.createApp({ data() { return { month: '', months: ['Jan', 'Feb', 'Apr', 'May', 'June', 'July', 'Aug'] } }, mounted() { this.updateScrollNextTick() }, methods: { addMessage() { if(this.month == ''){ return } this.months.push(this.month) this.month = '' this.updateScrollNextTick() }, updateScrollNextTick () { let scrolledHeight = this.$refs.scrolledHeight.clientHeight this.$nextTick(() => { this.$refs.listScroll.scrollTo({ behavior: 'smooth', top: scrolledHeight }) }) } }, }) .mount("#app") </script>
Sample address: https://codepen.io/ammezie/pen/OJpOvQE
Main part:
Running result:
In the above code snippet , we want to get a smooth scrolling down effect when a new item is added to the list. Take a look at the code and try modifying it to remove the nextTick
and you'll lose that smooth scrolling effect. You can also try using setTimeout
instead of nextTick
.
In this article, we explored how nextTick works. We take a closer look at how it differs from normal JavaScript setTimeout and cover practical use cases.
English original address: https://blog.logrocket.com/understanding-nexttick-in-vue-js/
Author: Chimezie Enyinnaya
Translated Author: Front-end Xiaozhi
Reprint address: https://segmentfault.com/a/1190000040246186
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of $nextTick VS setTimeout, see their differences. For more information, please follow other related articles on the PHP Chinese website!