0
Vue.js · Advanced Vue.js
New technique
Lifecycle hooks
Every component is created, shown on the page and one day removed. You can run code at each of those moments.
<script setup> runs while the component is being created, before its HTML is on the page: too early for work that needs the real DOM.
Lifecycle hooks fill that gap: you hand Vue a function, and Vue calls it at the right moment. Anything you start, like a timer or a listener on window, you stop when the component goes away, or it keeps running in the background.
<script setup>
import { onMounted, onUnmounted } from 'vue';
let timer;
onMounted(() => {
timer = setInterval(tick, 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
</script>onMounted: the component is on the page; its DOM elements exist.onUpdated: the DOM was just re-rendered after a change.onUnmounted: the component was removed. Clean up timers and listeners here.- In the Options API these are
mounted,updatedandunmounted(Vue 2 called the last onedestroyed).