The role of vue.nextTick

        A few years ago, when I first started writing vue, I encountered the problem of dom update. The following are the notes at that time, and I thought it was very interesting.

Vue operates dom, adding or deleting dom encountered problems:

1. Phenomenon:

By viewing the console console, using jq to get dom is always a step slower: that is, getting the dom rendered last time; using native js to get dom, it seems that you can get the current changed dom;

        But here comes the problem! The console looks like the number displayed by the console is the same as the actual number, but the length of the console is still the same as the length obtained by jq! js cannot get the last newly generated dom element!

 2. Analysis:

        In the vue project, vue monitors the change of data and updates the dom; through the console directly, the second step is to get the dom and update the data, and the third step is to start updating the dom. The dom has not been updated every time it is printed, so the obtained It is the dom before the update; it has nothing to do with jq or js.

Three, the solution:

        Method 1: Add a timer setTimeout(fn, 100) to the method of obtaining dom, and wait until the dom is updated before proceeding to console.
         Method 2. View the vue method and get a vue this.$nextTick() method, which delays the callback until the next dom update cycle.
Use it immediately after modifying the data, and then wait until the dom is updated to execute.

 

Four. Summary

        We sometimes encounter situations where we need to obtain dom in projects, such as echarts. But often the completion of the data update does not mean that the dom element is also rendered, so we need a method to execute the next callback function after the dom element is cyclically updated, which is nextTick.

//1、修改数据

vm.msg = 'Hello'

//2、DOM 未更新

Vue.nextTick(function () {
  
    //3、DOM 更新了

})

 

If you don't accumulate steps, you can't reach thousands of miles, and if you don't accumulate small streams, you can't form rivers and seas. come on!

Guess you like

Origin blog.csdn.net/Hello_MrShu/article/details/127110396