Lifecycle hooks คือฟังก์ชันที่ให้คุณเรียกใช้โค้ดในช่วงเวลาที่เฉพาะเจาะจงในการเผื่อประสิทธิ์ของส่วนประกอบ — การสร้าง การติดตั้งเข้า DOM การอัปเดต และการลบ ใน Composition API พวกเขาคือฟังก์ชันที่คุณเรียกใช้ภายใน setup
Hooks หลักตามลำดับ
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>
