Let's break it down simply
Every component passes through create, mount, update, and unmount stages. Run any code that needs the DOM inside onMounted. Clean up timers, event listeners, and subscriptions in onUnmounted.
vue
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const width = ref(0)
const measure = () => { width.value = window.innerWidth }
onMounted(() => {
measure()
window.addEventListener('resize', measure)
})
onUnmounted(() => window.removeEventListener('resize', measure))
</script>
<template><p>Viewport: {{ width }}px</p></template>You should see
Viewport: 1280pxTry it yourself
Write a timer component that increments every second, and clear the interval when it unmounts.
Lifecycle Hooks — Vue.js