目录

Component Lifecycle

Throughout the lifecycle of a component, some methods are triggered in a specific phase. Currently, the following lifecycle methods are supported:

Defining Lifecycle Methods

A lifecycle method can be defined in a top-level parameter of the Component constructor or declared in the lifetimes field. The lifetimes field is recommended because it has the highest priority and overrides the method with the same name in the top-level parameter.

The sample code snippet is as follows:

Component({
  lifetimes: {
    attached: function () {
      // Executed when the component instance enters the page node tree.
    },
    detached: function () {
      // Executed when the component instance is removed from the page node tree.
    },
  },
  // The following describes the old definition:
  created: function () {
    // Executed when the component instance is created.
  },
  detached: function () {
    // Executed when the component instance is removed from the page node tree.
  },
  // ...
})

You can also write lifecycle methods in behaviors, which will not be overridden by methods with the same name in other behaviors. Note that if a component directly or indirectly references the same behavior multiple times, the lifecycle methods in the behavior are executed only once during an execution period.

The available lifecycle methods are as follows.

Name

Parameter

Description

created

N/A

Executed when a component instance is created.

attached

N/A

Executed when a component instance enters the page node tree.

ready

N/A

Executed after the component layout at the rendering layer is complete.

detached

N/A

Executed when a component instance is removed from the page node tree.

Lifecycle of the Page Where the Component Exists

When a component needs to obtain the status change of the page where it exists, for example, the display and hiding changes, you can use the pageLifetimes methods to listen for them. These methods are lifecycle methods of the page where the component exists.

The sample code snippet is as follows:

Component({
  pageLifetimes: {
    show: function () {
      // Triggered when the page is displayed.
    },
    hide: function () {
      // Triggered when the page is hidden.
    },
    resize: function (size) {
      // Triggered when the page size changes.
    }
  }
})

The available lifecycle methods are as follows.

Name

Parameter

Description

show

N/A

Executed when the page where the component exists is displayed.

hide

N/A

Executed when the page where the component exists is hidden.