Skip to content

生命周期概览

生命周期钩子只能在组件 setup 同步阶段注册,也就是宏组件顶层。

ts
import { defineHtml, onMounted, onUnmounted } from "@elfui/core";

onMounted(() => {
  console.log("mounted");
});

onUnmounted(() => {
  console.log("unmounted");
});

export const Demo = defineHtml(`<p>Demo</p>`);

生命周期列表

API时机
onBeforeMount首次渲染提交前
onMounted最终 DOM 与 template ref 就绪后
onBeforeUpdate响应式 DOM 更新前
onUpdated响应式 DOM 更新后
onBeforeUnmount释放资源和 DOM 前
onUnmounted组件完全断开后
onActivatedKeepAlive 组件激活时
onDeactivatedKeepAlive 组件失活时
onAttributeChanged被观察的 host attribute 改变后
onErrorCaptured后代组件或生命周期操作发生错误时

onMounted 可以返回清理函数。卸载时会按后注册先清理的顺序执行:位于 onBeforeUnmount 之后,且早于组件 DOM 和作用域释放。

ts
onMounted(() => {
  const resource = createResource();
  return () => resource.destroy();
});

钩子可以返回 Promise。ElfUI 不会等待它再继续挂载或卸载时序,但 Promise rejection 会进入 onErrorCaptured 和应用 errorHandler。异步 onMounted 也可以最终返回清理函数;如果组件已经卸载,ElfUI 会立即执行这个迟到的清理函数。

TIP

onAttributeChanged((name, oldValue, newValue) => {}) 适合兼容未声明为 prop 的原生 attribute;已声明 props 的常规数据流优先使用 props 和响应式绑定。