May 17, 2021 WeChat Mini Program Development Document
The life cycle of a component refers to functions of the component itself that are automatically triggered at a particular point in time or when special framework events are encountered.
One of the most important lifecycles is the create attached detached, which contains the most important point in the life flow of a component instance.
The lifecycle method can be defined directly in the first-level parameters of the Component constructor.
Since the base library version 2.2.3, the life cycle of a component can also be declared within the lifetimes field (this is the recommended approach, with the highest priority).
Code example:
Component({
lifetimes: {
attached: function() {
// 在组件实例进入页面节点树时执行
},
detached: function() {
// 在组件实例被从页面节点树移除时执行
},
},
// 以下是旧式的定义方式,可以保持对 <2.2.3 版本基础库的兼容
attached: function() {
// 在组件实例进入页面节点树时执行
},
detached: function() {
// 在组件实例被从页面节点树移除时执行
},
// ...
})
Lifecycle methods can also be written in Behaviors, and will not be covered with each other in other Behaviors.But note that if a component is directly or indirectly references the same behavior, the lifecycle function in this Behavior will only be once in an execution timing.
The full life cycle available is as shown in the following table.
Life cycle | Parameters | Describe | The lowest version |
---|---|---|---|
created | No | Executed when the component instance was just created | 1.6.3 |
attached | No | Executed when a component instance enters the page node tree | 1.6.3 |
ready | No | Executed after the component is laid out at the view layer | 1.6.3 |
moved | No | Executed when a component instance is moved to another location in the node tree | 1.6.3 |
detached | No | Executed when a component instance is removed from the page node tree | 1.6.3 |
error |
Object Error
|
Executed whenever a component method throws an error | 2.4.1 |
There are also special lifecycles that are not very relevant to components, but sometimes components need to be informed for internal processing. S uch a lifecycle is called the "life cycle of the page on which the component is located" and is defined in the pageLifetimes definition segment. The life cycles available include:
Life cycle | Parameters | Describe | The lowest version |
---|---|---|---|
show | No | Executed when the page on which the component is located is displayed | 2.2.3 |
hide | No | Executed when the page on which the component is located is hidden | 2.2.3 |
resize |
Object Size
|
Executed when the size of the page on which the component is located changes | 2.4.0 |
Code example:
Component({
pageLifetimes: {
show: function() {
// 页面被展示
},
hide: function() {
// 页面被隐藏
},
resize: function(size) {
// 页面尺寸变化
}
}
})