组件生命周期
自定义组件用 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() {}
});自定义组件
{
"component": true,
"id": "probe",
"body": [
{
"type": "card",
"children": [
{
"type": "text",
"text": "组件状态",
"style": {
"fontWeight": "bold"
}
},
{
"type": "title",
"text": "{{phase}}"
},
{
"type": "notice",
"text": "来源 {{from}} · 本实例自己的日志"
},
{
"type": "list",
"bind": "logs",
"item": {
"type": "notice",
"text": "{{item.text}}"
}
}
]
}
]
}当前页面
{
"title": {
"text": "组件生命周期",
"fontSize": 18,
"color": "#FFFFFF",
"background": "#006A65"
},
"style": {
"background": "#F5F5F5",
"padding": 12
},
"body": [
{
"type": "row",
"style": {
"gap": 8
},
"children": [
{
"type": "button",
"text": "隐藏组件",
"onTap": "onConceal"
},
{
"type": "button",
"text": "显示组件",
"onTap": "onReveal"
}
]
},
{
"type": "probe",
"id": "inline",
"showIf": "showProbe",
"params": {
"from": "正文"
},
"onLog": "onLog"
},
{
"type": "space",
"height": 8
},
{
"type": "text",
"text": "父页收到的日志",
"style": {
"fontWeight": "bold"
}
},
{
"type": "list",
"bind": "logs",
"empty": "还没有日志",
"item": {
"type": "notice",
"text": "{{item.text}}"
}
}
]
}组件
组件状态
未创建
来源 · 本实例自己的日志
暂无数据
父页收到的日志
还没有日志
方法
| 时机 | 方法 |
|---|---|
实例创建,带父节点 params | created(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。数据怎么和父页来回,见 父页交互。
