生命周期钩子让你在组件生命的特定时刻运行代码——创建、挂载到 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>
