Lifecycle Hooks
Hooks for Vue 1.x
-
initCalled synchronously after the instance has been initialized and prior to any initial data observation. -
createdCalled synchronously after the instance is created. This occurs prior to $elsetup, but afterdata observation,computed properties,watch/event callbacks, andmethodshave been setup. -
beforeCompileImmediately prior to compilation of the Vue instance. -
compiledImmediately after compilation has completed. All directivesare linked but still prior to$elbeing available. -
readyOccurs after compilation and $elare complete and the instance is injected into the DOM for the first time. -
attachedOccurs when $elis attached to the DOM by adirectiveor instance calls$appendTo(). -
detachedCalled when $elis removed/detached from the DOM or instance method. -
beforeDestroyImmediately before the Vue instance is destroyed, but is still fully functional. -
destroyedCalled after an instance is destroyed. All bindingsanddirectiveshave already been unbound and child instances have also been destroyed.
Using in an Instance
Since all lifecycle hooks in Vue.js are just functions, you can place any of them directly in the instance declaraction.
//JS
new Vue({
el: '#example',
data: {
...
},
methods: {
...
},
//LIFECYCLE HOOK HANDLING
created: function() {
...
},
ready: function() {
...
}
});Common Pitfalls: Accessing DOM from the ready() hook
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.
})
}
}