微信小程序具有一套生命周期函数,这些函数会在小程序的不同阶段被触发,开发者可以在这些函数中执行相应的操作。以下是微信小程序的生命周期函数:
App 实例生命周期:
onLaunch(options): 小程序初始化时触发,全局只触发一次。
App({
onLaunch: function (options) {
console.log("App launched with options:", options);
}
});
onShow(options): 小程序启动或从后台进入前台时触发。
App({
onShow: function (options) {
console.log("App showed with options:", options);
}
});
onHide(): 小程序从前台进入后台时触发。
App({
onHide: function () {
console.log("App hidden");
}
});
onError(error): 小程序发生错误时触发。
App({
onError: function (error) {
console.error("App error:", error);
}
});
Page 页面生命周期:
onLoad(options): 页面加载时触发,一个页面只会调用一次。
Page({
onLoad: function (options) {
console.log("Page loaded with options:", options);
}
});
onShow(): 页面显示/切入前台时触发。
Page({
onShow: function () {
console.log("Page showed");
}
});
onReady(): 页面初次渲染完成时触发。
Page({
onReady: function () {
console.log("Page ready");
}
});
onHide(): 页面隐藏/切入后台时触发。
Page({
onHide: function () {
console.log("Page hidden");
}
});
onUnload(): 页面卸载时触发。
Page({
onUnload: function () {
console.log("Page unloaded");
}
});
Component 组件生命周期:
created(): 在组件实例刚刚被创建时执行。
Component({
created: function () {
console.log("Component created");
}
});
attached(): 在组件实例进入页面节点树时执行。
Component({
attached: function () {
console.log("Component attached");
}
});
ready(): 在组件布局完成后执行,此时可以获取节点信息(需要在 attached 中设置 data,然后在 ready 中访问)。
Component({
ready: function () {
console.log("Component ready");
}
});
moved(): 在组件实例被移动到节点树另一个位置时执行。
Component({
moved: function () {
console.log("Component moved");
}
});
detached(): 在组件实例被从页面节点树移除时执行。
Component({
detached: function () {
console.log("Component detached");
}
});