Page

更新时间:
复制 MD 格式

The Page constructor creates and manages mini program page instances, including display rendering, user interaction, data binding, and lifecycle events.

A Page object represents a single page in your application and handles its display and user interactions. Each page corresponds to a subdirectory. Page is a constructor that creates page instances.

Page initialization

  • Provide initial data for the page's first rendering:

    <view>{{title}}</view>
    <view>{{array[0].user}}</view>
    Page({
    data: {
      title: 'Alipay',
      array: [{user: 'li'}, {user: 'zhao'}]
    }
    })
  • Define interactive behavior by specifying a response function in the page script:

    <view onTap="handleTap">click me</view>

    A user click calls the handleTap method:

    Page({
    handleTap() {
      console.log('yo! view tap!')
    }
    })
  • Re-render a page by calling this.setData in the page script.

    <view>{{text}}</view>
    <button onTap="changeText"> Change normal data </button>

    Tapping the button calls the changeText method.

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

    Calling this.setData in changeText re-renders the page.

Page()

Page() accepts an object that specifies initial data, lifecycle functions, and event handler functions.

//index.js
Page({
  data: {
    title: "Alipay"
  },
  onLoad(query) {
    // Page loads
  },
  onReady() {
    // Page loading is complete
  },
  onShow() {
    // Page is displayed
  },
  onHide() {
    // Page is hidden
  },
  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
  },
  viewTap() {
    // Event handler
    this.setData({
      text: 'Set data for update.'
    })
  },
  go() {
    // Redirect with parameters. Read xx from the query in the onLoad function of page/index.
    my.navigateTo('/page/index?xx=1')
  },
  customData: {
    hi: 'alipay'
  }
})

The Page() object parameters:

Property

Type

Description

data

Object or Function

Initial data or a function that returns initial data.

onTitleClick

Function

Triggered when the title is clicked.

onOptionMenuClick

Function

Triggered when the extra navigation bar icon is clicked. Requires base library 1.3.0 or later. Use my.canIUse('page.onOptionMenuClick') to check support.

onPageScroll

Function({scrollTop})

Triggered when the page scrolls.

onLoad

Function(query: Object)

Triggered when the page loads.

onReady

Function

Triggered when the page's initial rendering is complete.

onShow

Function

Triggered when the page is displayed.

onHide

Function

Triggered when the page is hidden.

onUnload

Function

Triggered when the page is unloaded.

onPullDownRefresh

Function

Triggered when the page is pulled down.

onReachBottom

Function

Triggered when you scroll to the bottom of the page.

onShareAppMessage

Function

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

Other

Any

You can add custom functions or properties to the object parameter and access them with this.

Note

If the data is an object, modifying it on one page affects all other instances of that page.

Lifecycle methods

  • onLoad: Called once when the page loads. The query parameter contains the object passed from my.navigateTo and my.redirectTo.

  • onShow: Called each time the page is displayed.

  • onReady: Called once after initial rendering completes. The page can now interact with the view layer. Set interface properties such as my.setNavigationBar after this callback.

  • onHide: Called when the page is hidden, such as when navigating via my.navigateTo or switching bottom tabs.

  • onUnload: Called when the page is unloaded by my.redirectTo or my.navigateBack.

Event handler functions

  • onPullDownRefresh: Listens for the pull-to-refresh event. Enable pullRefresh in the window option of `app.json` first. Call my.stopPullDownRefresh to stop the animation after data loads.

  • onShareAppMessage: Called when a user shares the page. Share.

Page.prototype.setData()

setData sends data from the logic layer to the view layer and updates this.data.

Note

Directly modifying `this.data` does not update the page state and may cause data inconsistency. Avoid large data payloads in a single call.

setData accepts an object whose keys can be data paths such as array[2].message or a.b.c.d. These paths do not need to be predefined in this.data.

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>
Page({
  data: {
    text: 'test',
    array: [{text: 'a'}],
    object: {
      text: 'blue'
    }
  },
  changeTitle() {
    // Incorrect! Do not directly modify 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'
    })
  }
})

getCurrentPages()

getCurrentPages() returns the current page stack as an array, where the first element is the home page and the last is the current page. The following example checks whether the stack depth is five:

if(getCurrentPages().length === 5) {
  my.redirectTo('/xx');
} else {
  my.navigateTo('/xx');
}
Note

Do not modify the page stack. Modifications can cause routing and state errors.

The framework maintains current pages in a stack. Route changes affect the stack as follows:

Routing method

Page stack behavior

Initialization

A new page is pushed onto the stack.

Open a new page

A new page is pushed onto the stack.

Page redirection

The current page is popped from the stack, and the new page is pushed onto the stack.

Return to previous page

The current page is popped from the stack.

Tab switch

All pages are popped from the stack. Only the new tab page remains.

page.json

You can configure the window appearance for each page in a [page_name].json file.

Page configuration supports only window-related items, so the window key is not required. Page-level settings override the window settings in app.json.

You can also use the optionMenu property to configure a navigation icon. Clicking the icon triggers the onOptionMenuClick event.

file

Type

Required

Description

optionMenu

Object

No

Requires base library 1.3.0 or later. Adds an extra icon to the navigation bar. Currently supports the icon property. The icon value accepts an HTTP/HTTPS URL or a base64 string. Recommended size: 30 x 30 px.

Example:

{
  "optionMenu": {
    "icon": "https://img.alicdn.com/tps/i3/T1OjaVFl4dXXa.JOZB-114-114.png"
  }
}

Page style

Every page has a page root element. Use it to set properties such as height or background color.

page {
  background-color: #fff;
}