Vue.nextTick () introduction and usage scenarios

Each is very curious why this is, and then still do not understand after Baidu. Today, it is good to thoroughly understand this is doing it! !

First look at the document vue

nextTick (), the callback function is a time delay after the next update data call DOM, is simple to understand: when the data is updated, the rendered DOM, the automatic execution of the function

Use scene
1.Vue life cycle created () DOM function of operating the hook must be placed Vue.nextTick () callback function, the reason is created () function executes when the hook is not loaded DOM, so at this stage into operation of DOM is invalid. Here it is sure to DOM js code into operation Vue.nextTick () callback function. Corresponding hook function is mounted, because the hooking function executes all DOM mount has completed.
2. When the project you want to do something based on the new DOM DOM after changing the data elements of the new DOM js series of operations need to put Vue.nextTick () callback function; popular understanding is: Change after the data when you want to use js immediate operation a new view of the need to use it.

Vue.nextTick (callback) using the principle:
the reason is, Vue is asynchronous update dom, once the data changes observed, Vue will open a queue, and then change the data observed in the same event loop (event loop) among push feed watcher queue. If the watcher is triggered repeatedly, it will only be pushed to queue once. Such buffering behavior can effectively remove the unnecessary duplication of data resulting from the calculation and DOm operation. And when the next event loop, Vue will empty the queue, and make the necessary DOM updates.
When you set vm.someData = 'new value', DOM is not updated immediately, but in the asynchronous queue is cleared, that is only necessary to perform an update DOM updates when the next event cycle begins. At this point if you want to do certain things based on the updated DOM status, problems will arise. . In order to complete the update DOM Vue wait data after change, can be used immediately after the data change Vue.nextTick (callback). So the callback function will be called after the DOM update is complete.

Guess you like

Origin www.cnblogs.com/JiAyInNnNn/p/11468261.html