A lot of people talk about how they can handle asynchrony, but they don’t know exactly why nextTick is used, what problem it solves, and what it will do without it.

specify

A deferred callback is performed after the next DOM update loop ends. Use this method immediately after modifying the data to get the updated DOM. Problem solved: In some cases, dom operations need to be performed immediately after data changes. In this case, the DOM obtained is still the DOM obtained before data refresh, which cannot meet the requirements. In this case, $nextTick is used.

NextTick (function () {// DOM updated}) // Use as a Promise (new since 2.1.0, NextTick ().then(function () {// DOM updated})Copy the code

For example

For example, if a Vue component contains child components, the instance’s lifecycle hook function does not promise that all child components will be mounted at once, but sometimes we want the entire view to perform some operations after rendering, so we can use vm.$nextTick instead

Mounted:mounted: function () {
  this.$nextTick(function () {
      // do something after view render completed...})}Copy the code

When we modify the data in the instance or trigger the event that changes the data, the DOM updates asynchronously until the view is updated. Whenever Vue observes a data change, Vue opens a queue and buffers all data changes that occur in the same event loop.

If the same watcher is triggered more than once, it will only be pushed into the queue once. This removal of duplicate data while buffering is important to avoid unnecessary computation and DOM manipulation. Then, in the next event loop, “TICK,” Vue refreshes the queue and performs the actual (de-duplicated) work. So if you make multiple changes to uniform data in the same event loop, the result will only be rendered from the last change.

For example, when you set vm.someData = ‘new value’, the component does not immediately re-render. When the queue is refreshed, the component updates with the next “tick” when the event loop queue is empty. To do something after the data changes and wait for Vue to finish updating the DOM, use vue.nexttick (callback) immediately after the data changes. This callback will be called after the DOM update is complete.