There is a special API in vue, nextTick. According to the explanation of the official document, it can execute a callback after the DOM update is completed, the usage is as follows:
// Modify the data vm.msg = ' Hello ' // DOM has not been updated Vue.nextTick ( function () { // DOM updated ))
Although the MVVM framework does not recommend access to the DOM, sometimes it does have such a demand, especially when working with third-party plug-ins, it is inevitable to perform DOM operations.
NextTick provides a bridge to ensure that we are operating on the updated DOM.
1. Examples
Let's start with an example to understand the DOM update and nextTick
its role in Vue .
template
<div class="app"> <div ref="msgDiv">{{msg}}</div> <div v-if="msg1">Message got outside $nextTick: {{msg1}}</div> <div v-if="msg2">Message got inside $nextTick: {{msg2}}</div> <div v-if="msg3">Message got outside $nextTick: {{msg3}}</div> <button @click="changeMsg"> Change the Message </button> </div>
Vue example
new Vue({ el: '.app', data: { msg: 'Hello Vue.', msg1: '', msg2: '', msg3: '' }, methods: { changeMsg() { this.msg = "Hello world." this.msg1 = this.$refs.msgDiv.innerHTML this.$nextTick(() => { this.msg2 = this.$refs.msgDiv.innerHTML }) this.msg3 = this.$refs.msgDiv.innerHTML } } })
Before clicking
![](https://upload-images.jianshu.io/upload_images/3985563-b6bb266285e8d232.png?imageMogr2/auto-orient/strip|imageView2/2/w/152/format/webp)
After clicking
![](https://upload-images.jianshu.io/upload_images/3985563-f49bff3190724514.png?imageMogr2/auto-orient/strip|imageView2/2/w/341/format/webp)
It can be known from the figure that the content displayed by msg1 and msg3 is before conversion, and the content displayed by msg2 is after conversion. The root cause is that the DOM update in Vue is asynchronous (detailed explanation later).
Understand nextTick
the main application scenarios and reasons below.
created()
The DOM operation performed by the hook function of the Vue life cycle must be placed inVue.nextTick()
the callback function
When the created()
hook function is executed, the DOM does not actually perform any rendering. At this time, the DOM operation is in vain, so here we must put Vue.nextTick()
the js code of the DOM operation into the callback function. Corresponding to this is the mounted()
hook function, because all the DOM mounting and rendering are completed when the hook function is executed, and there will be no problem with any DOM operation in this hook function at this time.
- An operation to be performed after the data changes, and this operation needs to use the DOM structure that changes with the data change, this operation should be put into
Vue.nextTick()
the callback function.