Component lifecycle
Lifecycle hooks are functions Vue calls at key moments: creating, mounting, updating and destroying a component.
In this page:
Syntax
export default {
created() { },
mounted() { },
updated() { },
beforeUnmount() { },
unmounted() { }
}
Component lifecycle
Hooks include created, mounted, updated, beforeUnmount and unmounted (setup covers the earliest phase). mounted is the place to touch the DOM or start timers, and unmounted or beforeUnmount is where you clean up.
In Vue 3 the Options names beforeDestroy and destroyed were renamed.
Note:
Clean up timers and listeners in beforeUnmount to avoid memory leaks.
Example: Component lifecycle
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p>{{ msg }}</p>
</div>
<script>
const log = [];
const app = Vue.createApp({
data() { return { msg: "hi" }; },
created() { log.push("created"); },
beforeMount() { log.push("beforeMount"); },
mounted() { log.push("mounted"); this.msg = "changed"; },
updated() { log.push("updated"); },
beforeUnmount() { log.push("beforeUnmount"); },
unmounted() { log.push("unmounted"); },
});
app.mount("#app");
Vue.nextTick(() => { app.unmount(); console.log(log.join(" -> ")); });
</script>
</body>
</html>
<!-- Output:
console: created -> beforeMount -> mounted -> updated -> beforeUnmount -> unmounted
-->
Live Example
Related Topics
Common Mistakes
- Accessing the DOM in created
- Not cleaning up intervals
- Using Vue 2 hook names
Chapter Summary
- created runs before mounting
- mounted runs after DOM insertion
- updated runs after re-render
- unmounted is for cleanup
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: