页面生命周期
每个页面目录的 page.js 使用 Page({}) 注册。未声明的方法不会调用。this 为传入对象。
本章只讲页面什么时候被打开、显示、关掉。滚动、点击、滑动见 页面事件。下拉刷新见 下拉刷新。
生命周期只有这五个:onLoad / onShow / onReady / onHide / onUnload。
右侧预览会按真实顺序调用。页面上的「调用记录」和浏览器控制台都会打印。
javascript
Page({
data: {
logs: []
},
pushLog(text) {
console.log(text);
var logs = (this.data.logs || []).slice();
logs.push({ text: text });
this.setData({ logs: logs });
},
onLoad(params) {
this.pushLog('onLoad:当前页面第一次打开,参数 ' + JSON.stringify(params || {}));
},
onShow() {
this.pushLog('onShow:当前页面显示');
},
onReady() {
this.pushLog('onReady:当前页面首次显示完成');
},
onHide() {
this.pushLog('onHide:当前页面被盖住或切到其它页');
},
onUnload() {
this.pushLog('onUnload:当前页面关闭');
}
});{
"title": {
"text": "生命周期",
"fontSize": 18,
"color": "#FFFFFF",
"background": "#006A65"
},
"style": {
"background": "#F5F5F5",
"padding": 12
},
"body": [
{
"type": "notice",
"text": "进入顺序:onLoad → onShow → onReady。点「打开详情」走 onHide;返回后底层页只走 onShow。"
},
{
"type": "text",
"text": "调用记录",
"style": {
"fontWeight": "bold"
}
},
{
"type": "list",
"bind": "logs",
"item": {
"type": "notice",
"text": "{{item.text}}"
}
},
{
"type": "button",
"text": "打开详情",
"action": {
"type": "navigate",
"page": "detail"
}
}
]
}UI
进入顺序:onLoad → onShow → onReady。点「打开详情」走 onHide;返回后底层页只走 onShow。
调用记录
暂无数据
方法
| 时机 | 方法 |
|---|---|
| 页面第一次打开,带跳转参数 | onLoad(params) |
| 页面显示(含再次显示、从二级页返回) | onShow |
| 第一次显示完成,只一次 | onReady |
| 页面被盖住或切到其它 Tab | onHide |
| 页面关闭(二级页返回、退出项目) | onUnload |
调用顺序
首次进入:onLoad(params) → onShow → onReady(每个页面实例只一次)。离开时 onHide。关掉页面(二级页返回、退出项目)才 onUnload。从二级页返回、或切回已经打开过的 Tab,只走 onShow,不重新 onLoad。
| 场景 | 行为 |
|---|---|
| 底部 Tab 切换 | 当前页 onHide,实例保留。第一次进目标 Tab:onLoad → onShow → onReady。再切回来只走 onShow,数据和滚动还在。首页 onLoad 的 params 为 {} |
navigate 打开二级页 | 当前页 onHide。新页 onLoad(params) → onShow → onReady |
| 嵌套自定义组件 | 组件走 created / attached / detached,不是页面生命周期。见 组件生命周期 |
| 返回 | 二级页 onUnload,底层页 onShow,不重新 onLoad |
页面数据
data 为页面数据。模板 {{hello}} 与 "bind": "tasks" 均从此取值。常在 onLoad 里 this.setData 填入。
this.setData / this.appendData 按字段更新。表单输入写回 this.data,不触发整页刷新。因 showIf 新出现的节点会整页重绘。跳转、提示、标题、弹层、加载见 页面跳转 和 页面事件 · 页面方法。
| 写法 | 说明 |
|---|---|
data: { hello: '你好', tasks: [] } | 初始值 |
this.setData({ hello: '张三', tasks: items }) | 一次写入多份数据;列表整表替换 |
this.setData({ 'user.name': '运营A' }) | 点分路径 |
this.data.hello = '张三' | 改单个字段并刷新 |
this.appendData('tasks', more) | 向 data.tasks 末尾追加 |
setInterval + setData | 定时刷新,例如 组件 · Text 里的时钟 |
未写 bind 时,list / grid 的 id 当作 bind。表单 name(或 id)与 data 的键同名,list 项里的 name 也会做 {{ }} 替换。
