Page registration

更新时间:
复制 MD 格式

Page(object: Object)

To register a miniapp page, define Page() in a .js file within the /pages directory. This function accepts an object as a parameter that specifies the page's initial data, lifecycle callbacks, event handlers, and other details.

The following code shows a basic page:

// pages/index/index.js
Page({
  data: {
    title: "Alipay",
  },
  onLoad(query) {
    // Page loads
  },
  onShow() {
    // Page shows
  },
  onReady() {
    // Page loading is complete
  },
  onHide() {
    // Page hides
  },
  onUnload() {
    // Page is closed
  },
  onTitleClick() {
    // Title is clicked
  },
  onPullDownRefresh() {
    // Page is pulled down
  },
  onReachBottom() {
    // Page is pulled to the bottom
  },
  onShareAppMessage() {
   // Return custom sharing information
  },
  // Event handler object
  events: {
    onBack() {
      console.log('onBack');
    },
  },
  // Custom event handler
  viewTap() {
    this.setData({
      text: 'Set data for update.',
    });
  },
  // Custom event handler
  go() {
    // Navigate with parameters. Read the type from the query in the onLoad function of page/ui/index.
    my.navigateTo({url:'/page/ui/index?type=mini'});
  },
  // Custom data object
  customData: {
    name: 'alipay',
  },
});

Page lifecycle

The following diagram illustrates the lifecycle of a page object.

A miniapp is primarily managed by a view thread (Webview) and an app service thread (Worker). The view thread and the app service thread run concurrently.

  1. After the app service thread starts, it runs app.onLaunch and app.onShow to create the app. Then, it runs page.onLoad and page.onShow to create the page. At this point, the app service thread waits for a notification from the view thread that initialization is complete.

  2. When the view thread completes initialization, it notifies the app service thread. The app service thread then sends the initial data to the view thread for rendering. The view thread completes the initial rendering.

  3. After the initial rendering is complete, the view thread enters a ready state and notifies the app service thread. The app service thread then calls the page.onReady function and enters an active state.

  4. After the app service thread enters the active state, any data modification triggers the view thread to render the changes.

    • When the page switches to the background, the app service thread calls the page.onHide function and enters a persistent state.

    • When the page returns to the foreground, the page.onShow function is called, and the app service thread enters the active state.

    • When you navigate back or redirect to another page, the page.onUnload function is called to destroy the current page.

Object properties

Property

Type

Description

Minimum version

data

Object | Function

Initial data or a function that returns initial data

events

Object

Event handler object

1.13.7

onLoad

Function(query: Object)

Triggered when the page loads

onShow

Function

Triggered when the page is displayed

onReady

Function

Triggered when the page is rendered for the first time

onHide

Function

Triggered when the page is hidden

onUnload

Function

Triggered when the page is unloaded

onShareAppMessage

Function(options: Object)

Triggered when the share button in the upper-right corner is clicked

onTitleClick

Function

Triggered when the title is clicked

onOptionMenuClick

Function

Triggered when an extra icon in the navigation bar is clicked

1.3.0

onPopMenuClick

Function

1.3.0

onPullDownRefresh

Function({from: manual|code})

Triggered when the page is pulled down

onPullIntercept

Function

Triggered when the pull-down action is interrupted

1.11.0

onTabItemTap

Function

Triggered when a tabItem is clicked

1.11.0

onPageScroll

Function({scrollTop})

Triggered when the page scrolls

onReachBottom

Function

Triggered when the page is pulled up to the bottom

Other

Any

Developers can add any function or property to the object. These can be accessed using this in the page's functions.

Page data object data

You can set data to specify the initial data for a page. If data is an object, it is shared by all pages. This means that if you navigate away from the page and then return, the data from the last visit is displayed instead of the initial data. To resolve this issue, you can use one of the following two methods:

  • Set data as immutable data:

    Page({
    data: { arr:[] },
    doIt() {
     this.setData({arr: [...this.data.arr, 1]});
    },
    });
    Note

    Do not directly modify this.data. This action does not change the page state and can cause data inconsistency.

    The following example contains an error:

    Page({
    data: { arr:[] },
    doIt() {
     this.data.arr.push(1); // Do not do this!
     this.setData({arr: this.data.arr});
    }
    });
  • Set data as page-specific data (not recommended):

    Page({
    data() { return { arr:[] }; },
    doIt() {
     this.setData({arr: [1, 2, 3]});
    },
    });

Lifecycle functions

onLoad(query: Object)

This function is triggered when the page loads and is called only once for each page. The query parameter is the query object passed by my.navigateTo and my.redirectTo.

Property

Type

Description

query

Object

Parameters in the path of the current page.

onShow()

This function is triggered when the page is displayed or switched to the foreground.

onReady()

This function is triggered when the page is rendered for the first time and is called only once for each page. It indicates that the page is ready and can interact with the view layer.

You can configure interface settings, such as my.setNavigationBar, after the onReady function is complete.

onHide()

This function is triggered when the page is hidden or switched to the background. Examples include navigating to another page using my.navigateTo or switching tabs at the bottom of the page.

onUnload()

This function is triggered when the page is unloaded. Examples include redirecting to another page using my.redirectTo or navigating back using my.navigateBack.

Page event handlers

onShareAppMessage(options: Object)

This function is triggered when a user clicks the share button in the options menu in the upper-right corner or a share button within the page. For more information, see Share.

onTitleClick()

This function is triggered when the title is clicked.

onOptionMenuClick()

This function is triggered when the options menu button in the upper-right corner is clicked.

onPopMenuClick()

This function is triggered when the options menu button in the upper-right corner is clicked.

onPullDownRefresh({from: manual | code})

This function is triggered when you pull down to refresh the page. You must first enable pullRefresh in the window option of the app.json file. After the data is refreshed, you can call my.stopPullDownRefresh to stop the pull-to-refresh animation on the current page.

onPullIntercept()

This function is triggered when the pull-down action is interrupted.

onTabItemTap(object: Object)

This function is triggered when a tabItem is clicked.

Property

Type

Description

from

String

Click source

pagePath

String

Page path of the clicked tabItem

text

String

Button text of the clicked tabItem

index

Number

Index of the clicked tabItem, starting from 0

onPageScroll({scrollTop})

This function is triggered when the page scrolls. The scrollTop parameter indicates the distance the page has scrolled from the top.

onReachBottom()

This function is triggered when the page is scrolled to the bottom.

events

Note

To make your code more concise, you can use the new events object to handle events. Event handlers defined in the events object are equivalent to the event functions that are directly exposed on the page instance. The events object is supported from version 1.13.7 and later.

Event

Type

Description

Minimum version

onBack

Function

Triggered when the page returns

1.13.7

onKeyboardHeight

Function

Triggered when the keyboard height changes

1.13.7

onOptionMenuClick

Function

Triggered when the menu button in the upper-right corner is clicked

1.13.7

onPopMenuClick

Function

Triggered when the generic menu button in the upper-right corner is clicked

1.13.7

onPullIntercept

Function

Triggered when the pull-down action is interrupted

1.13.7

onPullDownRefresh

Function({from: manual|code})

Triggered when the page is pulled down

1.13.7

onTitleClick

Function

Triggered when the title is clicked

1.13.7

onTabItemTap

Function

Triggered after a tabItem is clicked and the tab is switched

1.13.7

beforeTabItemTap

Function

Triggered when a tabItem is clicked but before the tab is switched

1.13.7

Sample code:

Page({
  data: {
    text: 'This is page data.'
  },
  onLoad(){
    // Set a custom menu
    my.setCustomPopMenu({
      menus:[
        {name: 'Menu 1', menuIconUrl: 'https://menu1'},
        {name: 'Menu 2', menuIconUrl: 'https://menu2'},
      ],
    })
  },
  events:{
    onBack(){
      // Triggered when the page returns
    },
    onKeyboardHeight(e){
      // Triggered when the keyboard height changes
      console.log('Keyboard height:', e.height)
    },
    onOptionMenuClick(){
      // Triggered when the menu button in the upper-right corner is clicked
    },
    onPopMenuClick(e){
      // Triggered when a custom menu button in the generic menu in the upper-right corner is clicked
      console.log('Index of the custom menu item clicked by the user', e.index)
      console.log('Name of the custom menu item clicked by the user', e.name)
      console.log('menuIconUrl of the custom menu item clicked by the user', e.menuIconUrl)
    },
    onPullIntercept(){
      // Triggered when the pull-down action is interrupted
    },
    onPullDownRefresh(e){
      // Triggered when the page is pulled down. If the value of e.from is "code", the event is triggered by startPullDownRefresh. If the value is "manual", the event is triggered by a user pull-down action.
      console.log('Type of pull-to-refresh trigger', e.from)
      my.stopPullDownRefresh()
    },
    onTitleClick(){
      // Triggered when the title is clicked
    },
    onTabItemTap(e){
      // e.from is triggered after a tabItem is clicked and the tab is switched. If the value is "user", the event is triggered by a user click. If the value is "api", the event is triggered by switchTab.
      console.log('Type of tab change trigger', e.from)
      console.log('Path of the page corresponding to the clicked tab', e.pagePath)
      console.log('Text of the clicked tab', e.text)
      console.log('Index of the clicked tab', e.index)
    },
    beforeTabItemTap(){
      // Triggered when a tabItem is clicked but before the tab is switched
    },
  }
})

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

The setData function sends data from the logic layer to the view layer and changes the corresponding value of this.data.

Parameters:

Event

Type

Description

Minimum version

data

Object

The data to be changed

callback

Function

A callback function that is executed after the page rendering is updated.

Use my.canIUse('page.setData.callback') for compatibility processing. For more information, see 1.7.0

The Object uses a key: value format. This changes the value of the key in this.data to the new value. The key can be a data path, such as array[2].message or a.b.c.d. You do not need to pre-define the key in this.data.

Note the following when using this function:

  • Directly modifying this.data has no effect on the page state and can cause data inconsistency.

  • Only JSON-serializable data can be set.

  • Avoid setting too much data at once.

  • Do not set the value of any item in data to undefined. If you do, the item is not set, which may cause potential issues.

Sample code:

<view>{{text}}</view>
<button onTap="changeTitle"> Change normal data </button>
<view>{{array[0].text}}</view>
<button onTap="changeArray"> Change Array data </button>
<view>{{object.text}}</view>
<button onTap="changePlanetColor"> Change Object data </button>
<view>{{newField.text}}</view>
<button onTap="addNewKey"> Add new data </button>
<view>hello: {{name}}</view>
<button onTap="changeName"> Change name </button>
Page({
  data: {
    text: 'test',
    array: [{text: 'a'}],
    object: {
      text: 'blue',
    },
    name: 'taobao',
  },
  changeTitle() {
    // Incorrect! Do not directly modify the data in data.
    // this.data.text = 'changed data'  

    // Correct
    this.setData({
      text: 'ha',
    });
  },
  changeArray() {
    // You can directly use a data path to modify data.
    this.setData({
      'array[0].text': 'b',
    });
  },
  changePlanetColor(){
    this.setData({
      'object.text': 'red',
    });
  },
  addNewKey() {
    this.setData({
      'newField.text': 'c',
    });
  },
  changeName() {
    this.setData({
      name: 'alipay',
    }, () => { // Accept a callback function
      console.log(this); // this is the current page instance
      this.setData({ name: this.data.name + ', ' + 'welcome!'});
    });
  },
});

Page.prototype.$spliceData(data: Object, callback: Function)

Note

The $spliceData function is supported from version 1.7.2 and later. You can use my.canIUse('page.$spliceData') to check for compatibility. For more information, see Mini Program Base Libraries.

The spliceData method also sends data from the logic layer to the view layer. However, it provides higher performance than setData when handling long lists.

Parameters:

Event

Type

Description

data

Object

The data to be changed

callback

Function

A callback function that is executed after the page rendering is updated.

The Object uses a key: value format, which changes the value of the key in this.data to the new value. Note the following:

  • The key can be a data path, such as array[2].message or a.b.c.d. You do not need to pre-define the key in this.data.

  • The value is an array in the format [start, deleteCount, ...items]. The first element specifies the starting position for the operation. The second element specifies the number of elements to delete. The remaining elements are the data to insert. This format corresponds to the splice method for arrays in ES5.

Sample code:

<!-- pages/index/index.axml -->
<view class="spliceData">
  <view a:for="{{a.b}}" key="{{item}}" style="border:1px solid red">
    {{item}}
  </view>
</view>
// pages/index/index.js
Page({
  data: {
    a: {
      b: [1,2,3,4],
    },
  },
  onLoad(){
    this.$spliceData({ 'a.b': [1, 0, 5, 6] });
  },
});

Page output:

Page.prototype.$batchedUpdates(callback: Function)

This function updates data in batches.

Note

The $batchedUpdates function is supported from version 1.14.0 and later. You can use my.canIUse('page.$batchedUpdates') to check for compatibility. For more information, see Mini Program Base Libraries.

Parameters:

Event

Type

Description

callback

Function

Data operations in this callback function are batch updated.

Sample code:

// pages/index/index.js
Page({
  data: {
    counter: 0,
  },
  plus() {
    setTimeout(() => {
      this.$batchedUpdates(() => {
        this.setData({
          counter: this.data.counter + 1,
        });
        this.setData({
          counter: this.data.counter + 1,
        });
      });
    }, 200);
  },
});
<!-- pages/index/index.axml -->
<view>{{counter}}</view>
<button onTap="plus">+2</button>

In the preceding code sample:

  • Each time you click the button, the counter value of the page increases by 2.

  • If you place setData within this.$batchedUpdates, the data is transferred only once, even if multiple setData calls exist.