Vue.js Lifecycle Hooks Common Pitfalls: Accessing DOM from the `ready()` hook

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

A common usecase for the ready() hook is to access the DOM, e.g. to initiate a Javascript plugin, get the dimensions of an element etc.

The problem

Due to Vue's asynchronous DOM update mechanism, it's not guaranteed that the DOM has been fully updated when the ready() hook is called. This usually results in an error because the element is undefined.

The Solution

For this situation, the $nextTick() instance method can help. This method defers the execution of the provided callback function until after the next tick, which means that it is fired when all DOM updates are guaranteed to be finished.

Example:

module.exports {
  ready: function () {
    $('.cool-input').initiateCoolPlugin() //fails, because element is not in DOM yet.
    
    this.$nextTick(function() {
      $('.cool-input').initiateCoolPlugin() // this will work because it will be executed after the DOM update.
    })
  }
}


Got any Vue.js Question?