All Products
Search
Document Center

Page registration

Last Updated: Feb 04, 2021

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:

  1. // pages/index/index.js
  2. Page({
  3. data: {
  4. title: "Alipay",
  5. },
  6. onLoad(query) {
  7. // Page loading
  8. },
  9. onShow() {
  10. // Page display
  11. },
  12. onReady() {
  13. // Page loading completed
  14. },
  15. onHide() {
  16. // Page hiding
  17. },
  18. onUnload() {
  19. // Page is closed
  20. },
  21. onTitleClick() {
  22. // Title is clicked
  23. },
  24. onPullDownRefresh() {
  25. // Page is pulled down
  26. },
  27. onReachBottom() {
  28. // Page reaches the bottom
  29. },
  30. onShareAppMessage() {
  31. // Return custom shared message
  32. },
  33. // Event object
  34. events: {
  35. onBack() {
  36. console.log('onBack');
  37. },
  38. },
  39. // Custom event handlers
  40. viewTap() {
  41. this.setData({
  42. text: 'Set data for update.',
  43. });
  44. },
  45. // Custom event handlers
  46. go() {
  47. // Page jumps with a parameter. Get type by using the query method of onLoad function from the URL: page/ui/index.
  48. my.navigateTo({url:'/page/ui/index?type=mini'});
  49. },
  50. // Custom data object
  51. customData: {
  52. name: 'alipay',
  53. },
  54. });

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.
  1. Page({
  2. data: { arr:[] },
  3. doIt() {
  4. this.setData({arr: [...this.data.arr, 1]});
  5. },
  6. });
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:

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

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:

  1. Page({
  2. data: {
  3. text: 'This is page data.'
  4. },
  5. onLoad(){
  6. // Sets custom menus.
  7. my.setCustomPopMenu({
  8. menus:[
  9. {name: 'Menu 1', menuIconUrl: 'https://menu1'},
  10. {name: 'Menu 2', menuIconUrl: 'https://menu2'},
  11. ],
  12. })
  13. },
  14. events:{
  15. onBack(){
  16. // Triggered when the system returns to the current page.
  17. },
  18. onKeyboardHeight(e){
  19. // Triggered when the height of the keypad changes.
  20. console.log('Keypad height:', e.height)
  21. },
  22. onOptionMenuClick(){
  23. // Triggered when the menu in the upper-right corner is tapped.
  24. },
  25. onPopMenuClick(e){
  26. // Triggered when a custom menu in the general menu in the upper-right corner is tapped.
  27. console.log('Index of the custom menu tapped by the user', e.index)
  28. console.log('Name of the custom menu tapped by the user', e.name)
  29. console.log('menuIconUrl of the custom menu tapped by the user', e.menuIconUrl)
  30. },
  31. onPullIntercept(){
  32. // Triggered when the pull-down operation is stopped.
  33. },
  34. onPullDownRefresh(e){
  35. // 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.
  36. console.log('Trigger type of pull-to-refresh', e.from)
  37. my.stopPullDownRefresh()
  38. },
  39. onTitleClick(){
  40. // Triggered when the title is tapped.
  41. },
  42. onTabItemTap(e){
  43. // 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.
  44. console.log('Trigger type of the tab change)', e.from)
  45. console.log('Path to the page that corresponds to the tapped tab', e.pagePath)
  46. console.log('Text on the tapped tab', e.text)
  47. console.log('Index of the tapped tab', e.index)
  48. },
  49. beforeTabItemTap(){
  50. // Triggered when a tabItem is tapped but before the tab is switched to the destination tab.
  51. },
  52. }
  53. })

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:

  1. <view>{{text}}</view>
  2. <button onTap="changeTitle"> Change normal data </button>
  3. <view>{{array[0].text}}</view>
  4. <button onTap="changeArray"> Change Array data </button>
  5. <view>{{object.text}}</view>
  6. <button onTap="changePlanetColor"> Change Object data </button>
  7. <view>{{newField.text}}</view>
  8. <button onTap="addNewKey"> Add new data </button>
  9. <view>hello: {{name}}</view>
  10. <button onTap="changeName"> Chane name </button>
  1. Page({
  2. data: {
  3. text: 'test',
  4. array: [{text: 'a'}],
  5. object: {
  6. text: 'blue',
  7. },
  8. name: 'taobao',
  9. },
  10. changeTitle() {
  11. // Wrong setting. Do not directly modify the data indicated by the data parameter.
  12. // this.data.text = 'changed data'
  13. // Right setting.
  14. this.setData({
  15. text: 'ha',
  16. });
  17. },
  18. changeArray() {
  19. // You can modify data by using the path to the data.
  20. this.setData({
  21. 'array[0].text': 'b',
  22. });
  23. },
  24. changePlanetColor(){
  25. this.setData({
  26. 'object.text': 'red',
  27. });
  28. },
  29. addNewKey() {
  30. this.setData({
  31. 'newField.text': 'c',
  32. });
  33. },
  34. changeName() {
  35. this.setData({
  36. name: 'alipay',
  37. }, () => { // Accepts transferring the callback function.
  38. console.log(this); // This parameter indicates the current page instance.
  39. this.setData({ name: this.data.name + ', ' + 'welcome!'});
  40. });
  41. },
  42. });

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:

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

Output on the page:

  1. 1
  2. 5
  3. 6
  4. 2
  5. 3
  6. 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:

  1. // pages/index/index.js
  2. Page({
  3. data: {
  4. counter: 0,
  5. },
  6. plus() {
  7. setTimeout(() => {
  8. this.$batchedUpdates(() => {
  9. this.setData({
  10. counter: this.data.counter + 1,
  11. });
  12. this.setData({
  13. counter: this.data.counter + 1,
  14. });
  15. });
  16. }, 200);
  17. },
  18. });
  1. <!-- pages/index/index.axml -->
  2. <view>{{counter}}</view>
  3. <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.