Skip to content

组件生命周期 ​

自定义组件用 Component({}) 注册。未声明的方法不会调用。this 为传入对象。

只有三个:created / attached / detached。不是页面的 onLoad / onShow / onReady / onHide / onUnload。页面生命周期见 页面生命周期。

右侧预览会按真实顺序调用。组件卡片上的日志、父页列表、浏览器控制台都会打印。点「隐藏组件 / 显示组件」看 detached / attached。上面是 probe 组件代码,下面是当前页;父页 body 里有 { "type": "probe" }。

javascript
Component({
  data: {
    logs: [],
    phase: '未创建'
  },
  created(props) {},
  attached() {},
  detached() {}
});

方法 ​

时机方法
实例创建,带父节点 paramscreated(props)
插入界面(节点 showIf 为真)attached
从界面拿掉(showIf 为假、父页卸载)detached

created 每个实例只一次。节点反复显示隐藏:第一次 created → attached,之后只走 attached / detached,不再 created。

调用顺序 ​

页面 body 里的组件:随父页创建,created(props) → attached。父页关掉时 detached。切 Tab 页面不卸载,组件保持 attached。

节点写了 showIf:条件为假时 detached,再为真时只走 attached。

弹窗若要用组件,把 { "type": "choose" } 写在弹层 body 里。弹层显示时组件 attached,隐藏时 detached。外壳仍由 popup 负责,见 组件 · Popup。

场景行为
父页第一次打开可见组件 created → attached
把节点 showIf 写成假该组件 detached
再把 showIf 写成真该组件 attached(不再 created)
父页 navigate 到二级页父页 onHide。可见组件保持 attached
父页关闭树上组件 detached
父页切到其它 Tab父页 onHide。组件保持 attached(页面未卸载)

组件看不到父页变量,也不走 onReady。数据怎么和父页来回,见 父页交互。