NextTick method

The Vue implementation is responsive, not that the DOM changes immediately after the data changes, but that the DOM is updated according to a certain strategy

In simple terms, Vue does not update the view immediately after the data is changed. Instead, it updates the view after all the data changes in the same event loop are complete.

Data changes in Vue are synchronous and can be obtained after updating; However, DOM updates are asynchronous and need to be retrieved instantly with nextTick

To put it bluntly, becauseVueIs executed asynchronouslyDOMUpdated, want to operate updated immediatelyDOMYou need to use$nextTick

NextTick purposes

In the Created and Mounted phases, the nextTick method is also used if you need to manipulate rendered views.

Official documentation:

Note that Mounted does not promise that all child components will also be mounted together. If you want to wait until the entire view is rendered, replace Mounted with vm.$nextTick

mounted: function () {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been rendered})}Copy the code

Other Application Scenarios

  • Click the button to display the input box that was hidden with V-show = false and get focus.
showsou(){
  this.showit = true / / modify v - show
  document.getElementById("keywords").focus()  
    // In the first tick, the input box is not available, so the focus is not available
}
Copy the code

Is amended as:

showsou(){
  this.showit = true
  this.$nextTick(function () {
    // DOM is updated
    document.getElementById("keywords").focus()
  })
}
Copy the code
  • Click to get the element width.
<div id="app">
    <p ref="myWidth" v-if="showMe">{{ message }}</p>
    <button @click="getMyWidth">Gets the p element width</button>
</div>

getMyWidth() {
    this.showMe = true;
    //this.message = this.$refs.myWidth.offsetWidth;
    TypeError: this.$refs.myWidth is undefined
    this.$nextTick(() = >{
        // the dom element is updated and the attributes of the p element are retrieved
        this.message = this.$refs.myWidth.offsetWidth; })}Copy the code