Lifecycle hooks in setup
In the Composition API lifecycle hooks are functions such as onMounted and onUnmounted that you call inside setup.
In this page:
Syntax
import { onMounted, onUnmounted } from 'vue';
setup() {
onMounted(() => {
// runs after mounting
});
onUnmounted(() => {
// cleanup
});
}
Lifecycle hooks in setup
Import or access onMounted, onUpdated, onUnmounted, onBeforeMount and friends and pass them a callback. You can call the same hook several times, which lets composables register their own setup and cleanup logic. created and beforeCreate are replaced by setup itself.
Note:
Clean up timers and listeners in onUnmounted inside the same composable that created them.
Example: Lifecycle hooks in setup
<!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>{{ ticks }} ticks</p></div>
<script>
const events = [];
let tickRef;
const app = Vue.createApp({
setup() {
const ticks = Vue.ref(0);
tickRef = ticks;
let timer;
Vue.onMounted(() => { events.push("mounted"); timer = setInterval(() => ticks.value++, 5); });
Vue.onUnmounted(() => { events.push("unmounted"); clearInterval(timer); });
return { ticks };
},
});
app.mount("#app");
setTimeout(() => { app.unmount(); console.log(events.join(" -> "), "| ticks counted while mounted:", tickRef.value > 0); }, 40);
</script>
</body>
</html>
<!-- Output:
console: mounted -> unmounted | ticks counted while mounted: true
-->
Live Example
Related Topics
Common Mistakes
- Calling hooks outside setup
- Forgetting cleanup
- Expecting a created hook
Chapter Summary
- onMounted, onUpdated, onUnmounted
- Call them inside setup
- Several calls are allowed
- setup replaces created
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: