8
Author: Chimezie Enyinnaya
Translator: Frontend Xiaozhi
Source: blog

Are dreaming, dry, micro-channel search [World] big move concerned about this in the morning still in the dishwashing dishwashing wisdom.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

A front-end developer (Xiaozhi) walked into a Vue bar. Xiao Zhi ordered his favorite cocktail: Nuxt. The bartender is working hard to make it. Then he started nagging himself.

$nextTick under the example method of Vue 3, and was surprised. Xiaozhi
He has been using Vue for a while, and he has become accustomed to writing $watch and $emit as example methods. So, what is $nextTick used for? The Vue documentation says that it "[defers] callback, executed after the next DOM update cycle".

But Xiaozhi didn't believe it.

He went on to describe how he tried to do this:

this.loadingAnimation = true
this.startVeryLongCalculation()
this.completeVeryLongCalculation()
this.loadingAnimation = false

it works. Why?

What does nextTick do?

nextTick accepts a callback function that is delayed until the next DOM update cycle. This is just a way of saying Vue, "Hey, if you want to execute a function after the DOM is updated (this rarely happens), I hope you use nextTick instead of setTimeout ."

Vue.nextTick(() => {}) // syntax

The parameters setTimeout and nextTick will be discussed shortly below. We use this example to visualize the behavior 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 display 2021 . It's not that if you remove nextTick , you won't get the same result. 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 to update the DOM to 2021 , and finally transfers control to the browser, and the browser will display 2021 .

So far, we have studied that nextTick inserts a callback function into the callback queue and executes the function when appropriate.

You may be interested in nextTick . The callback in 06158f99464204 is used as a microtask in the event loop. nextTick of source code clear that, " nextTick behavior use the micro-task queue, by local Promise.then or MutationObserver to visit."

setTimeout vs nextTick

Another way to execute a function after the DOM is updated is to use JavaScript's setTimeout() function.

We replace nextTick setTimeout the above code:

<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>

Run this code snippet. First see 3 and then 2021 . It happens quickly, so if you don't see this behavior, you need to refresh your browser.

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 transfers control to the browser, and now the browser displays 2021 .

nextTick is implemented on Promise and MutationObserver (IE 6-10 and Opera Mini browsers), using s etTimeout as a fallback method. For Promise and MutationObserver (IE 10), it prefers setImmediate .

When to use nexttick

  • When you want to use setTimeout
  • When you want to make sure that the DOM reflects your data
  • When trying to perform asynchronous operations, Uncaught (in promise) DOMException such as 06158f994643f0 are encountered. Remember, Vue updates the DOM asynchronously

Finally, 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>

Example address: https://codepen.io/ammezie/pen/OJpOvQE

main part:

image.png

operation result:

In the above code snippet, we want to get a smooth scrolling down effect when a new item is added to the list. nextTick through the code, try to modify it, remove 06158f9946452e, you will lose the smooth scrolling effect. You can also try to use setTimeout instead of nextTick .

Summarize

In this article, we explored how nextTick works. We further understood the difference between it and ordinary JavaScript setTimeout, and introduced actual use cases.

~End, I am Xiaozhi, and I am going to educate a front-end girl.

possible bugs in 16158f994645c7 editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://blog.logrocket.com/understanding-nexttick-in-vue-js/

comminicate

The article is continuously updated every week, you can search for [Great Move to the World] Read it for the first time, reply [Benefit] are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhizhi has been included, welcome to Star.


王大冶
68.1k 声望105k 粉丝