Lifecycle Hooks
Every Vue component goes through a predictable lifecycle — created, mounted onto the page, updated as data changes, and eventually removed — and lifecycle hooks let you run your own code at each of those specific moments.
The two hooks you'll use most: mounted and unmounted
mounted fires once, right after the component has been inserted into the actual DOM — the right place for anything that needs a real element to exist, like fetching data to display or setting up a timer:
app.component('live-clock', {
data() {
return { time: new Date().toLocaleTimeString() }
},
mounted() {
console.log('Component mounted, starting timer')
this.timer = setInterval(() => {
this.time = new Date().toLocaleTimeString()
}, 1000)
},
unmounted() {
console.log('Component removed, clearing timer')
clearInterval(this.timer)
},
template: `<p>{{ time }}</p>`
})
Component mounted, starting timer (... ticks every second while on screen ...) Component removed, clearing timer
unmounted fires right before the component is torn down — the matching cleanup point for anything set up in mounted. Skipping this cleanup is a real bug: the setInterval would keep running and trying to update this.time on a component that no longer exists on the page.
updated: after a re-render
updated fires after the DOM has re-rendered in response to a reactive data change — useful for the rare case where you need to read something about the newly-updated DOM itself, like measuring an element's new size:
updated() {
console.log('Re-rendered. New height:', this.$el.offsetHeight)
}
The full order, start to finish
created → data and methods are set up, but nothing is on the page yet mounted → the component is now in the real DOM updated → fires each time reactive data causes a re-render (can fire many times) unmounted → the component has been removed from the page
.vue components replace the inline template strings used throughout this course.