ライフサイクルフックを使用すると、コンポーネントの人生における特定の時点でコードを実行できます — 作成、DOMへのマウント、更新、削除。Composition APIではこれらはsetup内部で呼び出す関数です。
主なフックの順序
vue
<script setup>
import { onMounted, onUpdated, onUnmounted, ref } from "vue";
const data = ref(null);
onMounted(() => {
// component is now in the DOM — fetch data, access elements, init libraries
fetchData().then(d => (data.value = d));
});
onUpdated(() => {
// runs after the DOM re-renders due to a reactive change
});
onUnmounted(() => {
// component is being removed — CLEAN UP here
clearInterval(timer);
window.removeEventListener("resize", handler);
});
</script>
