# Page(Object object)

Register a page in Weixin Mini Program.Accepts aObjecttype parameter that specifies the initial data of the page, a lifecycle callback, an event handler, etc.

# parameter

# Object object

attribute type Default values Required to fill in Introductions
data Object Initial data for the page
options Object Component options for the page, as in the Componentconstructoroptions, requires base library version {% version ('2.10.1')%}
behaviors String Array Intercomponent code reuse mechanism similar to mixins and traits, see behaviors , requires base library version {% version ('2.9.2')%}
onLoad function Lifecycle callback - listen for page loading
onShow function Lifecycle callback - listening for page display
onReady function Lifecycle callback - listen to the page's initial rendering complete
onHide function Lifecycle Tuning - Listen to Page Hidden
onUnload function Lifecycle callback - listening to page uninstall
onRouteDone function Lifecycle Tuning - Listening to the routing animation complete
onPullDownRefresh function Monitor the user's drop-down actions
onReachBottom function Handling functions for pull-bottom events on a page
onShareAppMessage function Users click on the top right corner to forward
onShareTimeline function The user clicks the "Forward to WeChat Moments" option at the top right corner.
onAddToFavorites function Users click on the top right corner to bookmark
onPageScroll function Handling functions for page scrolling trigger events
onResize function Triggered when page size changes, see Response to display area changes
onTabItemTap function When the current tab page is triggered by clicking tab
onSaveExitState function Retention status callback before page destruction
Other any Developers can add arbitrary functions or data to theObjectparameter, which can be accessed in a page's functions withthis. This attribute makes a deep copy when the page instance is created .

# sample code

//index.js
Page({
  data: {
    text: "This is page data."
  },
  onLoad: function(options) {
    // 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.
  },
  onShareAppMessage: function () {
    // return custom share data when user share.
  },
  onPageScroll: function() {
    // Do something when page scroll
  },
  onResize: function() {
    // Do something when page resize
  },
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  // Event handler.
  viewTap: function() {
    this.setData({
      text: 'Set some data for updating view.'
    }, function() {
      // this is setData callback
    })
  },
  customData: {
    hi: 'MINA'
  }
})

# data

Datais the initial data used for the first rendering of the page.

When the page is loaded,datais passed as] JSON character string from the logical layer to the render layer.Therefore, data indatamust be of the type that can be converted to] JSON [: character string, number, boolean, object, array.

The rendering layer can bind data via WXML .

Example code:

Preview with Developer Tool

<view>{{text}}</view>
<view>{{array[0].msg}}</view>
Page({
  data: {
    text: 'init data',
    array: [{msg: '1'}, {msg: '2'}]
  }
})

# Lifecycle callback function

Life cycle triggers and page routing See

# onLoad(Object query)

The page is triggered when it loads. A page is called only once, and you can get the parameters in the path to open the current page in the parameters of onLoad.

Parameters:

name type Introductions
query Object Open parameters in the path of the current page

# onShow()

Triggers when the page displays / when entering the front desk.

# onReady()

It is triggered when the page is first rendered. A page is only called once, which means that the page is ready to interact with the view layer.

Note: The API for setting the interface content is wx.setNavigationBarTitle ,Please proceed afteronReady.See Life Cycle

# onHide()

Triggers when the page is hidden / in the background.For example, wx.navigateTo or the bottomtabto switch to another page, Weixin Mini Program to switch into the background, etc.

# onUnload()

The page is triggered when it is unloaded.Such as wx.redirectTo or wx.navigateBack to other pages.

# onRouteDone()

The routing animation is triggered when it is finished.Such as wx.navigateTo when the page is fully pushed or wx.navigateBack when the page is fully restored.

# Page event handling function

# onPullDownRefresh()

Monitor the user's drop-down refresh events.

# onReachBottom()

Monitor the user's pull-bottom event.

# onPageScroll(Object object)

Monitor user sliding page events.

Object object :

attribute type Introductions
scrollTop Number How far the page has been scrolled vertically (in px)

Note: Define this method in the page only when needed. Do not define an empty method. To reduce the impact of unnecessary event distribution on rendering-logical layer communication. Note: Please avoid performingsetDatatoo often in onPageScroll to cause logic-rendering-layer communication .Especially when a large amount of data is transmitted at a time, it affects communication time.

# onAddToFavorites(Object object)

This interface is Beta version, Android version 7.0.15 support, temporarily only in the Android platform support

Monitor the user's behavior by clicking the "Bookmark" button on the menu in the upper right corner and customize the contents of the bookmarks.

Object object :

parameter type Introductions
webViewUrl String When the page contains a web-view component, returns the current [web-view ( )] url

This event handler needs to return an Object for custom collection:

field Introductions Default values
title Custom Title Page title or account name
imageUrl Customize the picture to show a length breadth ratio of 1: 1 Screenshot of the page
query Custom query fields Query for the current page

sample code

Page({
  onAddToFavorites(res) {
    // webview 页面返回 webViewUrl
    console.log('webViewUrl: ', res.webViewUrl)
    return {
      title: '自定义标题',
      imageUrl: 'http://demo.png',
      query: 'name=xxx&age=xxx',
    }
  }
})

# onShareAppMessage(Object object)

Listens to the user clicking the forwarding button within the page ( button componentopen-type = "share") or the behavior of the "forward" button in the upper-right menu, and customize the forward content.

Note: The upper-right menu displays the "forward" button only if this event handling function is defined

Object object :

parameter type Introductions Minimum version
from String 转发事件来源。

button:页面内转发按钮;

menu:右上角转发菜单
1.2.4
target Object If thefromvalue isbutton,Then thetargetis thebuttonthat triggers this forwarding event,Otherwiseundefined 1.2.4
webViewUrl String When the page contains a web-view component, returns the current [web-view ( )] url 1.6.4

This event handler needs to return an Object, which is used to customize the forwarding content, as follows:

Customise the content of the retweet Since the base library {% version ('2.8.1')%}, shared graphs support cloud images.

field Introductions Default values Minimum version
title Post a title Current Weixin Mini Program name
path Post the path The current page path, must be the full path beginning with /
imageUrl A custom image path, which can be a local file, a codepage file, or a graph of a network. Supports PNG and JPG. The length breadth ratio is 5: 4. Use the default screenshot 1.5.0
promise If this parameter exists, the resolve result will prevail. If it does not resolve within three seconds, the sharing will use the default parameter passed in above 2.12.0

sample code

Preview with Developer Tool

Page({
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '自定义转发标题'
        })
      }, 2000)
    })
    return {
      title: '自定义转发标题',
      path: '/page/user?id=123',
      promise 
    }
  }
})

# onShareTimeline()

Start from base library version 2.11.3. Please remaining backward compatible.

For details, see and share it on WeChat Moments.

Monitor the behavior of the "Share to WeChat Moments" button in the top-right menu and customize the shared content.

Note: The "Share to WeChat Moments" button will only appear in the top-right menu if an event handling function has been defined.

Customise the content of the retweet

The event handler returns an Object, which is used to customize the shared content. The custom page path is not supported. The return is as follows:

field Introductions Default values Minimum version
title Custom title, which is the title displayed on the list page of WeChat Moments Current Weixin Mini Program name
query Parameters carried in a custom page path, such as path?The "?" of a = 1 & b = 2The following part Parameters carried by the current page path
imageUrl Custom picture path, can be local file or graph of a network. Support PNG and JPG, show the image length breadth ratio is 1: 1. Use Weixin Mini Program Logo by default
promise If this parameter exists, the resolve result will prevail. If it does not resolve within three seconds, the sharing will use the default parameter passed in above 3.12.0

sample code

Page({
  onShareTimeline() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '自定义转发标题'
        })
      }, 2000)
    })
    return {
      title: '自定义转发标题',
      query: 'id=123',
      imageUrl: '/images/share.png',
      promise
    }
  }
})

# onResize(Object object)

Start from base library version 2.4.0. Please remaining backward compatible.

Triggers when the page size changes.See Response shows area changes

# onTabItemTap(Object object)

Start from base library version 1.9.0. Please remaining backward compatible.

Triggered when a tab is clicked

Object parameter explaination:

parameter type Introductions Minimum version
index String The ordinal number of the tabItem to be clicked, starting from 0 1.9.0
pagePath String The page path of the tabItem clicked 1.9.0
text String The button text that is clicked on the tabItem 1.9.0

Example code:

Page({
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  }
})

# onSaveExitState()

Start from base library version 2.7.4. Please remaining backward compatible.

Whenever Weixin Mini Program might be destroyed, the page callback functiononSaveExitStateis called to save the exit state .

# Component Event Handling Functions

Component event handlers can also be defined in page.Add the event binding to the components of the rendering layer, and when the event is triggered, the event handler defined in the Page is executed.

Example code:

Preview with Developer Tool

<view bindtap="viewTap"> click me </view>
Page({
  viewTap: function() {
    console.log('view tap')
  }
})

# Page.route

Start from base library version 1.2.0. Please remaining backward compatible.

Path to the current page of typeString.

Page({
  onShow: function() {
    console.log(this.route)
  }
})

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

The setDatafunction is used to send data from the logic layer to the view layer (asynchronously) and to change the value of the correspondingthis.data(synchronized).

# Parameter explaination

field type Required to fill in describe Minimum version
data Object yes The data to change this time.
callback Function no Callback function after rendering of interface update caused by setData 1.5.0

Objectwithkey: valueChange the value corresponding to thekeyinthis.data `` value

Among them,keycan be given in the form of a data path, allowing to change an item or an object's attribute in an array, such asarray[2].Message,a.b.c.dand need not be predefined in this.data.

NOTE:

  1. Modifying this.data directly without calling this.setData will not change the state of the page and will cause data inconsistency .
  2. Only JSONable data is supported.
  3. A single set of data can not exceed 1024kB, please try to avoid setting too much data at one time.
  4. Do not set the value of any item in the data toundefined, otherwise the item will not be set and some potential problems may be left behind.

Example code:

Preview with Developer Tool

<!--index.wxml-->
<view>{{text}}</view>
<button bindtap="changeText"> Change normal data </button>
<view>{{num}}</view>
<button bindtap="changeNum"> Change normal num </button>
<view>{{array[0].text}}</view>
<button bindtap="changeItemInArray"> Change Array data </button>
<view>{{object.text}}</view>
<button bindtap="changeItemInObject"> Change Object data </button>
<view>{{newField.text}}</view>
<button bindtap="addNewField"> Add new data </button>
// index.js
Page({
  data: {
    text: 'init data',
    num: 0,
    array: [{text: 'init data'}],
    object: {
      text: 'init data'
    }
  },
  changeText: function() {
    // this.data.text = 'changed data' // 不要直接修改 this.data
    // 应该使用 setData
    this.setData({
      text: 'changed data'
    })
  },
  changeNum: function() {
    // 或者,可以修改 this.data 之后马上用 setData 设置一下修改了的字段
    this.data.num = 1
    this.setData({
      num: this.data.num
    })
  },
  changeItemInArray: function() {
    // 对于对象或数组字段,可以直接修改一个其下的子字段,这样做通常比修改整个对象或数组更好
    this.setData({
      'array[0].text':'changed data'
    })
  },
  changeItemInObject: function(){
    this.setData({
      'object.text': 'changed data'
    });
  },
  addNewField: function() {
    this.setData({
      'newField.text': 'new data'
    })
  }
})

# Inter-page communication

Start from base library version 2.7.3. Please remaining backward compatible.

If a page is passed by another page wx.navigateTo Open, and a data channel is created between the two pages:

  • Open pages can be accessed viathis.getOpenerEventChannel ()Method to obtain aEventChannelobject;
  • Thesuccesscallback of wx.navigateToalso contains anEventChannelobject.

The twoEventChannelobjects can send and listen to events usingemitandonmethods.

Preview with Developer Tool