All Products
Search
Document Center

Mobile Platform as a Service:Page registration

Last Updated:May 26, 2023

Page(object: Object)

Define Page() in .js file of /pages directory, which is used for registering a Mini Program page and accept an object as an attribute, to specify information such as initial data, life cycle callback, and event processing of the page.

The following code snippet shows a basic page code:

// pages/index/index.js
Page({
  data: {
    title: "Alipay",
  },
  onLoad(query) {
    // Page loading
  },
  onShow() {
    // Page display
  },
  onReady() {
    // Page loading completed
  },
  onHide() {
    // Page hiding
  },
  onUnload() {
    // Page is closed
  },
  onTitleClick() {
    // Title is clicked
  },
  onPullDownRefresh() {
    // Page is pulled down
  },
  onReachBottom() {
    // Page reaches the bottom
  },
  onShareAppMessage() {
   // Return custom shared message
  },
  // Event object
  events: {
    onBack() {
      console.log('onBack');
    },
  },
  // Custom event handlers
  viewTap() {
    this.setData({
      text: 'Set data for update.',
    });
  },
  // Custom event handlers
  go() {
    // Page jumps with a parameter. Get type by using the query method of onLoad function from the URL: page/ui/index.
    my.navigateTo({url:'/page/ui/index?type=mini'});
  },
  // Custom data object
  customData: {
    name: 'alipay',
  },
});

Page life cycle

The following figure shows the life cycle of Page object.

Mini Program controls management mainly based on Webview and Worker. Webview and Worker run at the same time.

  1. After the application service thread has started, it will run app.onLaunch and app.onShow to complete creation of the app. Then it will run page.onLoad and page.onShow to complete creation of a Page. At this moment, this thread will wait for the view thread to notify it of the completion of initialization.
  2. The view thread notifies the application service thread after completing initialization. The application service thread then sends the initial data to the view thread for rendering. At this moment, the view thread completes rendering of the data for the first time.
  3. After the first rendering is complete, the view thread will enter the ready state and notify the application service thread, which will then call the function page.onReady and enter the active state.
  4. After the application service thread has entered the active state, it will notify the view thread to render the page every time the data is modified.
    • When the page is switched to the background, the application service thread will call the function page.onHide and enter the standby state.
    • When the page returns to the foreground, the application service thread will call the function page.onShow and enter the active state.
    • After the function for returning to the previous page or redirecting the page is called, the application service thread will call the function page.onUnload to destroy the page.

Descriptions of object attributes

Attribute Type Description The minimum version
data Object | Function The initial data or the function for returning the initialization data.
events Object The object of the event handling function. 1.13.7
onLoad Function(query: Object) Triggered when the page is loading.
onShow Function Triggered when the page is being displaying.
onReady Function Triggered when the initial rendering of the page is complete.
onHide Function Triggered when the page is being hidden.
onUnload Function Triggered when the page is being unloaded.
onShareAppMessage Function(options: Object) Triggered when the user shares the page by tapping the upper-right corner.
onTitleClick Function Triggered when the title is tapped.
onOptionMenuClick Function Triggered when the options icon in the navigation bar is tapped. 1.3.0
onPopMenuClick Function 1.3.0
onPullDownRefresh Function({from: manual|code}) Triggered when the page is pulled downward.
onPullIntercept Function Triggered when pulling downward is stopped. 1.11.0
onTabItemTap Function Triggered when a tabItem is tapped. 1.11.0
onPageScroll Function({scrollTop}) Triggered when the page is scrolled.
onReachBottom Function Triggered when the bottom of the page is reached by user pulling upward.
Others Any A developer can add to object any function or attribute, which can be accessed using this within a function of the page.

The object that stores data of a page - data

You can specify the initial data of a page by setting data. When data is an object, it is shared by all pages. This means when a user opens page A, returns to the previous page and then opens page A again, data of the previous page will be displayed instead of the initial data. In this case, the problem can be resolved using the following two methods:

  • Set data to be constant data.
Page({
 data: { arr:[] },
 doIt() {
   this.setData({arr: [...this.data.arr, 1]});
 },
});
Note: Do not directly modify this.data. Doing this will not change the status of the page and will cause inconsistent data.

For example, the following code is wrong:

Page({
 data: { arr:[] },
 doIt() {
   this.data.arr.push(1); // Never write code like this!
   this.setData({arr: this.data.arr});
 }
});
  • Set data to be unique data of the page (not recommended):
Page({
 data() { return { arr:[] }; },
 doIt() {
   this.setData({arr: [1, 2, 3]});
 },
});

Life cycle functions

onLoad(query: Object)

Triggered when the page is loaded. It is called only once by each page. query is the query object passed within my.navigateTo and my.redirectTo.

Attribute Type Description The minimum version
query Object The parameter for opening the path of the current page.

onShow()

Triggered when the page is displayed or switched to the foreground.

onReady()

Triggered when the initial rendering of the page is complete. It is called only once by each page. When it is called, it means the page is ready and can interact with the view layer.

Setting of the page, for example, my.setNavigationBar, must be done after onReady.

onHide()

Triggered when the page is hidden or switched to the background. For example, it is triggered when my.navigateTo is called to go to another page or the user switches to another tab at the bottom of the page.

onUnload()

Triggered when the page is unloaded. For example, it is triggered when a different page is opened by my.redirectTo or my.navigateBack.

Event handlers for a page

onShareAppMessage(options: Object)

Triggered when the share button in the general menu in the upper-right corner or a share button inside a page is tapped. For more details, see Share.

onTitleClick()

Triggered when the title is tapped.

onOptionMenuClick()

Triggered when the menu in the upper-right corner is tapped.

onPopMenuClick()

Triggered when the general menu in the upper-right corner is tapped.

onPullDownRefresh({from: manual | code})

Triggered when the page is pulled to refresh. This method can be used only when pullRefresh is enabled in the window attribute in the app.json file. For more information, see Set global configurations in app.json. After data is refreshed, the my.stopPullDownRefresh operation can be called to stop pull-to-refresh on the current page.

onPullIntercept()

Triggered when the pull-down operation is stopped.

onTabItemTap(object: Object)

Triggered when a tabItem is tapped.

Attribute Type Description The minimum version
from String The source of the tap operation.
pagePath String The path to the page where the tapped tabItem is located.
text String The text on the button that corresponds to the tapped tabItem.
index Number The serial number of the tapped tabItem. The serial numbers start from 0.

onPageScroll({scrollTop})

Triggered when the page is scrolled. The scrollTop attribute indicates the distance that the page is scrolled.

onReachBottom()

Triggered when the page is pulled up to the top.

events

Note: For brevity of the code, the platform provides a new event processing object named events. Existing events are equivalent to the events function exposed in the page instance. Events objects are supported since base library 1.13.7.
Event Type Description The minimum version
onBack Function Triggered when the system returns to the current page. 1.13.7
onKeyboardHeight Function Triggered when the height of the keypad changes. 1.13.7
onOptionMenuClick Function Triggered when the menu in the upper-right corner is tapped. 1.13.7
onPopMenuClick Function Triggered when the general menu in the upper-right corner is tapped. 1.13.7
onPullIntercept Function Triggered when the pull-down operation is stopped. 1.13.7
onPullDownRefresh Function({from: manual|code}) Triggered when the page is pulled downward. 1.13.7
onTitleClick Function Triggered when the title is tapped. 1.13.7
onTabItemTap Function Triggered after a tabItem is tapped and the tab is switched to the destination tab. 1.13.7
beforeTabItemTap Function Triggered when a tabItem is tapped but before the tab is switched to the destination tab. 1.13.7

Code sample:

Page({
  data: {
    text: 'This is page data.'
  },
  onLoad(){
    // Sets custom menus.
    my.setCustomPopMenu({
      menus:[
        {name: 'Menu 1', menuIconUrl: 'https://menu1'},
        {name: 'Menu 2', menuIconUrl: 'https://menu2'},
      ],
    })
  },
  events:{
    onBack(){
      // Triggered when the system returns to the current page.
    },
    onKeyboardHeight(e){
      // Triggered when the height of the keypad changes.
      console.log('Keypad height:', e.height)
    },
    onOptionMenuClick(){
      // Triggered when the menu in the upper-right corner is tapped.
    },
    onPopMenuClick(e){
      // Triggered when a custom menu in the general menu in the upper-right corner is tapped.
      console.log('Index of the custom menu tapped by the user', e.index)
      console.log('Name of the custom menu tapped by the user', e.name)
      console.log('menuIconUrl of the custom menu tapped by the user', e.menuIconUrl)
    },
    onPullIntercept(){
      // Triggered when the pull-down operation is stopped.
    },
    onPullDownRefresh(e){
      // Triggered when the page is pulled down. When e.from is set to code, the event is triggered by startPullDownRefresh. When e.from is set to manual, the event is triggered by the pull-down operation performed by the user.
      console.log('Trigger type of pull-to-refresh', e.from)
      my.stopPullDownRefresh()
    },
    onTitleClick(){
      // Triggered when the title is tapped.
    },
    onTabItemTap(e){
      // The e.from event is triggered after a tabItem is tapped and the tab is switched to the destination tab. When e.from is set to user, the event is triggered by a tap operation performed by the user. When e.from is set to api, the event is triggered by the switchTab operation called by the user.
      console.log('Trigger type of the tab change)', e.from)
      console.log('Path to the page that corresponds to the tapped tab', e.pagePath)
      console.log('Text on the tapped tab', e.text)
      console.log('Index of the tapped tab', e.index)
    },
    beforeTabItemTap(){
      // Triggered when a tabItem is tapped but before the tab is switched to the destination tab.
    },
  }
})

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

The setData method sends data from the logical layer to the view layer and changes the value of the this.data object.

The parameters are described as follows:

Event Type Description The minimum version
data Object The data that needs to be changed.
callback Function A callback function. The callback function is executed after page rendering is complete. The compatibility issue needs to be handled by using the my.canIUse('page.setData.callback') operation. For more information, see Introduction of the base library of the Mini Program component.

The value of Object is expressed in the key: value format. Set the value of key in the this.data object to the value of value. In particular, the key can be exported as a data path, such as array[2].message and a.b.c.d. You do not need to predefine keys in the this.data object.

Be aware of the following when you use the setData method:

  • Do not directly modify the this.data object. Otherwise, the status of the page cannot be changed, and data inconsistency will occur.
  • Only data that can be converted to the JSON format is supported.
  • Do not perform the operation on an excessive volume of data.
  • Do not set one or multiple attribute values of the data parameter to undefined. Otherwise, the attribute is ignored, which leads to some potential problems.

Code sample:

<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"> Chane name </button>
Page({
  data: {
    text: 'test',
    array: [{text: 'a'}],
    object: {
      text: 'blue',
    },
    name: 'taobao',
  },
  changeTitle() {
    // Wrong setting. Do not directly modify the data indicated by the data parameter.
    // this.data.text = 'changed data'  

    // Right setting.
    this.setData({
      text: 'ha',
    });
  },
  changeArray() {
    // You can modify data by using the path to the data.
    this.setData({
      'array[0].text': 'b',
    });
  },
  changePlanetColor(){
    this.setData({
      'object.text': 'red',
    });
  },
  addNewKey() {
    this.setData({
      'newField.text': 'c',
    });
  },
  changeName() {
    this.setData({
      name: 'alipay',
    }, () => { // Accepts transferring the callback function.
      console.log(this); // This parameter indicates the current page instance.
      this.setData({ name: this.data.name + ', ' + 'welcome!'});
    });
  },
});

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

Note: $spliceData is supported since base library 1.7.2. The compatibility issue can be handled by calling the my.canIUse(‘page.\$spliceData’) operation. For more information, see Introduction of the base library of the Mini Program component.

The spliceData method is also used to send data from the logical layer to the view layer. Different from the setData method, this data has higher performance in processing long lists.

The parameters are described as follows:

Event Type Description The minimum version
data Object The data that needs to be changed.
callback Function A callback function. The callback function is executed after page rendering is complete.

Object is expressed in the key: value format. Set the value of key in the this.data object to the value of value. The following content describes the parameters of the object:

  • key parameter can be a data path, such as array[2].message and a.b.c.d. You do not have to predefine this parameter in the this.data object.
  • value parameter is an array in the format [start, deleteCount, …items]). In the array, the first element is the start position of the operation, the second element is the number of deleted elements, and the remaining elements are inserted data. This parameter corresponds to the splice method in the array of es5.

Code sample:

<!-- 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] });
  },
});

Output on the page:

1
5
6
2
3
4

Page.prototype.$batchedUpdates(callback: Function)

Batch update the specified data.

Note: The $spliceData method is supported since base library 1.14.0. The compatibility issue can be handled by calling the my.canIUse(‘page.\$batchedUpdates’) operation. For more information, see Introduction of the base library of the Mini Program component.

The parameters are described as follows:

Event Type Description The minimum version
callback Function A callback function. The data involved in the callback function will be batch updated.

Code sample:

// 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 code above:

  • The value of counter on the page increases by 2 each time a button is tapped on the page.
  • The setData method is placed in this.$batchedUpdates. This ensures that the data is transmitted only once, regardless of how many times the setData method is invoked.