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.
While vue.js generally encourages developers to think in a data-driven way and avoid direct contact with the DOM, sometimes we have to. The Mounted () hook that you perform DOM operations on in vue must be placed in the vue.nexttick () callback.
Vue.$nextTick(callback), a callback to execute when the DOM changes after the update.
The Mounted () hook is mounted without rendering the DOM, so put the DOM manipulation in the vue.$nextTick() callback.
Vue.$nextTick() does not require a global Vue; this in the function callback is automatically bound to the current Vue instance.
Vue.component('example', { template: '<span>{{ message }}</span>', data: function () { return { message: }}, methods: {updateMessage: Function () {this.message = 'update' console.log(this.$el.textContent) // => 'update' this.$nextTick(function () {this.message = 'update' console.log(this. The console. The log (enclosing $el. TextContent) / / = > 'updated'}}}})Copy the code
$nextTick() returns a Promise object, so you can do the same thing with the new ES2016 async/await syntax:
methods: { updateMessage: Function () {this.message = 'update' console.log(this.$el.textContent) // => 'update' await this.$nextTick() Console. log(this.$el.textContent) // => 'Updated'}}Copy the code
Vue.nexttick (callback), which executes a callback after data changes.
To wait for Vue to finish updating the DOM after the data changes, use vue.nexttick () immediately after the data changes. This callback is intended to be called after the Dom update is complete.
<div id="example">{{message}}</div> var vm = new Vue({ el: '#example', data: { message: $el.textContent === 'new message' // false vue.nexttick (function () {$el.textContent === 'new Message '// false vue.nexttick (function () { vm.$el.textContent === 'new message' // true })Copy the code