Vue.js Lesson 8: Lifecycle Hooks
Lifecycle hooks run code at specific moments in a component’s life — when it mounts, updates, or is destroyed.
Lifecycle Order
<script setup>
import { onMounted, onUpdated, onUnmounted, onBeforeMount } from "vue";
// Runs BEFORE component is inserted into DOM
// (can't access DOM yet)
onBeforeMount(() => {
console.log("About to mount");
});
// Runs AFTER component is in the DOM
// (use for: fetch data, add event listeners, timers)
onMounted(() => {
console.log("Component mounted!");
fetchData();
window.addEventListener("resize", handleResize);
});
// Runs after every reactive update
onUpdated(() => {
console.log("Component updated!");
});
// Runs when component is removed
// (use for: cleanup timers, remove listeners)
onUnmounted(() => {
console.log("Component destroyed!");
window.removeEventListener("resize", handleResize);
});
</script>
Fetching Data on Mount
<script setup>
import { ref, onMounted } from "vue";
const posts = ref([]);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
posts.value = await res.json();
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
});
</script>
🏋️ Practice Task
Build a live clock component. Shows hours:minutes:seconds, updates every second. Start interval in onMounted. Clear interval in onUnmounted. Also fetch a random quote from https://api.quotable.io/random on mount. Show author and content.
💡 Hint: const timer = setInterval(() => time.value = new Date(), 1000). In onUnmounted: clearInterval(timer).