---
title: Page
---

## Page(config: Object)

Register a page of a miniapp. An `Object` parameter is used to specify the initial data, lifecycle callbacks, event handler functions, and other required data of the page.

## Parameter

| Property          | Type     | Default value | Required | Description                                                                      | Minimum version |
| ----------------- | -------- | ------------- | -------- | -------------------------------------------------------------------------------- | --------------- |
| data              | Object   |               |          | The initial data of the page.                                                    |
| onLoad            | function |               |          | The lifecycle callback to invoke when the page is loaded.                        |
| onShow            | function |               |          | The lifecycle callback to invoke when the page is displayed.                     |
| onReady           | function |               |          | The lifecycle callback to invoke when the page is initially rendered.            |
| onHide            | function |               |          | The lifecycle callback to invoke when the page is hidden.                        |
| onResize          | function |               |          | The lifecycle callback to invoke when the page is resized.                       |
| onUnload          | function |               |          | The lifecycle callback to invoke when the page is unloaded.                      |
| onReachBottom     | function |               |          | The handler function invoke when users swipe up to reach the bottom of the page. |
| onPullDownRefresh | function |               |          | The listener for the event in which users swipe down to refresh a page.          |

You can access the generated page instance by using the `this` keyword in the methods and lifecycle functions of the page.

## Page this instance

### Properties

| Property | Type   | Description                                 |
| -------- | ------ | ------------------------------------------- |
| route    | String | The path of the current page.               |
| options  | Object | The parameters passed to implement routing. |
| data     | Object | The page data.                              |

### Methods

| Method name           | Parameter         | Description                                                                                                          | Minimum version |
| --------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------- | --------------- |
| setData               | Object `newData`  | Sets data and renders the view layer.                                                                                |                 |
| selectComponent       | String `selector` | Uses the selector to search for a component instance node and returns the first matched component instance object.   |                 |
| selectAllComponents   | String `selector` | Uses the selector to search for component instance nodes and returns an array of matched component instance objects. |                 |
| getOpenerEventChannel |                   | Returns an EventChannel object.                                                                                      |                 |

## data

`data` is the **initial data** that is used to initially render the page.

To load a page, `data` is passed from the logic layer to the rendering layer in the `JSON` string format. Therefore, `data` must be in a format that you can convert to `JSON` type, such as a string, number, Boolean value, object, or array.

**Example**

```xml
<view>{{text}}</view>
<view>{{array[0].msg}}</view>
```

```js
Page({
  data: {
    text: 'init data',
    array: [{ msg: '1' }, { msg: '2' }],
  },
});
```

## Lifecycle

### onLoad(query: Object)

Triggered when a page is loaded. This function can be called only once for each page. In `onLoad`, you can get the parameter used in the path for opening the current page.

**parameters**

| Name  | Type   | Description                              |
| ----- | ------ | ---------------------------------------- |
| query | Object | The parameters in the current page path. |

```js
ty.navigateTo({
  url: 'hello/index?id=1',
});
```

```js
// hello/index.js
Page({
  onLoad(query) {
    // query = { id: 1 }
  },
});
```

### onShow()

Triggered when a page is displayed or switches to the foreground.

### onReady()

Triggered when a page is initially rendered. This function is called only once for each page, and indicates that the page is ready to interact with the view layer.

**Note:** Make the API requests such as [ty.setNavigationBarTitle](/en/miniapp/develop/miniapp/api/ui/navigation-bar/setNavigationBarTitle#tysetnavigationbartitle) to set UI content only after `onReady` is called.

### onHide()

Triggered when a page is hidden or switches to the background. For example, this function applies when [ty.navigateTo](/en/miniapp/develop/miniapp/api/route/navigateTo) is called or when the miniapp switches from a bottom `tab` to another page or to the background.

### onResize(options: Object)

Triggered when the miniapp page is resized.

**options fields description**

| Name              | Type   | Description                               |
| ----------------- | ------ | ----------------------------------------- |
| type              | string | `portrait` `landscape`                    |
| size.windowWidth  | Number | The width of the screen, in pixels (px).  |
| size.windowHeight | Number | The height of the screen, in pixels (px). |

```js
Page({
  onResize: function (options) {
    console.log(options.type);
    console.log(options.size.windowWidth);
    console.log(options.size.windowHeight);
  },
});
```

### onUnload()

Triggered when a page is unloaded. For example, this function applies when [ty.redirectTo](/en/miniapp/develop/miniapp/api/route/redirectTo) or [ty.navigateBack](/en/miniapp/develop/miniapp/api/route/navigateBack) is called to navigate to another page.

## Page event handlers

### onPullDownRefresh()

Listens for the event in which users swipe down to refresh a page.

- You must enable `enablePullDownRefresh` in the [window](/en/miniapp/develop/miniapp/framework/app/app-json#window) options or page settings of `app.json`.
- You can use [ty.startPullDownRefresh](/en/miniapp/develop/miniapp/api/ui/container/startPullDownRefresh) to trigger the action of swiping down and refreshing the page. The resulting animation is the same as that triggered by manual operations.
- After data is refreshed, [ty.stopPullDownRefresh](/en/miniapp/develop/miniapp/api/ui/container/stopPullDownRefresh) can be used to stop swiping down and refreshing the current page.

### onReachBottom()

Listens for the event in which users swipe up to reach the bottom of a page.

- You can set the trigger distance `onReachBottomDistance` in the [window](/en/miniapp/develop/miniapp/framework/app/app-json#window) options or page settings of `app.json`.
- This event will be triggered only once when users swipe within the trigger distance.

## Page component event triggers

You can define a component event handler in `Page`. Bind an [event](/en/miniapp/develop/miniapp/framework/event/interaction) with the rendering component. When the event is triggered, the event handler defined in `Page` is executed.

**Example:**

```xml
<view bind:tap="viewTap"> click me </view>

```

```js
Page({
  viewTap: function () {
    console.log('view tap');
  },
});
```

## Page.prototype.setData(data: Object, callback: Function)

The `setData` function is used to asynchronously transmit data from the logic layer to the view layer, and synchronously change the value of `this.data`.

**Parameters**
| Parameter | Type | Required | Description | Minimum version |
| ----------------------------------- | ------------ | --- | --- | --- |
| data | Object | Yes | The data to be modified. | ---|
| callback | Function | No | The callback to invoke when page rendering is triggered and finished by `setData`. | |

`Object` is expressed in the format of `key: value`. In `this.data`, the value of `key` is changed to the specified `value`.

You can set `key` to a data path, and modify an item of an array or an object property, such as `array[2].message` and `a.b.c.d`. You do not need to predefine `this.data`.

Things to note:

1. **If you modify `this.data` but do not call `this.setData`, the page status cannot be changed and data inconsistency might occur.**
2. You can only set data content that can be serialized, including: `String`, `Number`, `Boolean`, `Null`, `undefined`, `Object`, and `Array`. Other data types will be ignored.
3. Up to 1024 KB of data can be set in each call. We recommend that you do not set an excessive amount of data.
4. Do not set any `value` in `data` to `undefined`. Otherwise, this item will not be set, and certain potential problems might arise.

Example:

```xml
<view>{{text}}</view>
<button bind:tap="changeText"> Change normal data </button>
```

```js
Page({
  data: {
    text: 'init data',
  },
  changeText: function () {
    this.setData({
      text: 'changed data',
    });
  },
});
```

## Page.prototype.getOpenerEventChannel

If you call [ty.navigateTo](/en/miniapp/develop/miniapp/api/route/navigateTo) to navigate from one page to another page, a data channel is established between these pages.

- The `EventChannel` object is returned for the opened page after the method `this.getOpenerEventChannel()` is called.
- The `success` callback of [ty.navigateTo](/en/miniapp/develop/miniapp/api/route/navigateTo) contains an `EventChannel` object.

You can use the `emit` method to transmit events and `on` method to listen for events between these two `EventChannel` objects.


```js
// pages/previous/index.js
Page({
  onLoad: function () {
    // Opens a new page and passes data to it
    ty.navigateTo({
      url: '/pages/home/index',
      events: { // EventChannel is created only if events are specified
        // Listens for data sent back from the opened page
        acceptFromOpenerPage: (data) => {
          console.log(data); // Logs the received data from home page
        },
      },
      success: (eventChannel) => {
        // Sends data to the newly opened page using EventChannel
        eventChannel.emit('sendToOpenerPage', { data: 'Hello from previous page!' });
      },
    });
  },
});
```

```js
Page({
  onLoad: function () {
    // Retrieves the EventChannel created by the navigation action from the previous page
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel) {
      // Listens for the event sent from the previous page
      eventChannel.on('sendToOpenerPage', (data) => {
        console.log(data); // Logs the received data from previous page
        // Sends a response or additional data back to the previous page
        eventChannel.emit('acceptFromOpenerPage', { data: 'Hello from home page!' });
      });
    }
  }
});
```

## Example

```js
//index.js
Page({
  data: {
    text: 'This is page data.',
  },
  onLoad: function (query) {
    // Do some initialize when page load.
  },
  onShow: function () {
    // Do something when page show.
  },
  onReady: function () {
    // Do something when page ready.
  },
  onHide: function () {
    // Do something when page hide.
  },
  onUnload: function () {
    // Do something when page close.
  },
  onPullDownRefresh: function () {
    // Do something when pull down.
  },
  onReachBottom: function () {
    // Do something when page reach bottom.
  },
  // Event handler.
  viewTap: function () {
    this.setData(
      {
        text: 'Set some data for updating view.',
      },
      function () {
        // this is setData callback
      },
    );
  },
});
```
