tencent cloud

Feedback

Registration page

Last updated: 2024-04-10 16:14:22

    Page

    Page (Object) Constructor

    The Page(Object) function is used to register a webpage. It accepts an Object type argument, which designates the webpage's initial data, lifecycle callbacks, event handling functions, and so forth.
    Explanation of the Object parameter:
    Attribute
    Type
    Description
    object
    Initial data of the page
    fuction
    Lifecycle Callback - Monitoring Page Load
    fuction
    Lifecycle Callback - Monitoring Page Display
    fuction
    Lifecycle Callback - Monitoring Initial Page Rendering Completion
    fuction
    Lifecycle Callback - Monitoring Page Concealment
    fuction
    Lifecycle Callback - Monitoring Page Unload
    fuction
    Monitor User's Pull-down Actions
    fuction
    Handling function for events triggered by page pull-up
    fuction
    Handling function for events triggered by page scroll
    fuction
    User clicks the Favourite button in the top-right corner menu (supported by base library of Version 1.4.0 and later versions)
    fuction
    User clicks the Share button in the top right corner menu
    fuction
    Triggered when page size changes. See Responding to Display Area Changes for details.
    onCustomBack
    function
    The developer intercepts the default return callback of the page
    fuction
    Triggered when the current page is a Tab page and the Tab is clicked.
    Other
    any
    Developers can add any function or data to the Object parameter, which can be accessed in the page function via this.
    Sample Code
    // index.js
    Page({
    data: {
    text: 'This is page data.'
    },
    onLoad(options) {
    // Do some initialize when page load.
    },
    onReady() {
    // Do something when page ready.
    },
    onShow() {
    // Do something when page show.
    },
    onHide() {
    // Do something when page hide.
    },
    onUnload() {
    // Do something when page close.
    },
    onPullDownRefresh() {
    // Do something when pull down.
    },
    onReachBottom() {
    // Do something when page reach bottom.
    },
    onShareAppMessage() {
    // return custom share data when user share.
    },
    onAddToFavorites: function(res) {
    // return custom favorite data.
    },
    onPageScroll() {
    // Do something when page scroll
    },
    onResize() {
    // Do something when page resize
    },
    onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
    },
    // Event handler.
    viewTap() {
    this.setData({
    text: 'Set some data for updating view.'
    }, function () {
    // this is setData callback
    })
    },
    customData: {
    hi: 'MINA'
    }
    })
    Beyond the Page, as an advanced usage, pages can be created like custom components using component, thereby enabling the use of custom component features such as behaviors and so forth. For specific details, see the Component Constructor section.

    Initial Data

    data

    Data represents the initial data used for the first rendering of the page.
    Upon page load, data will be transferred from the logic layer to the rendering layer in the form of a JSON string. Therefore, the data within data must be a type convertible to JSON: string, number, boolean, object, array.
    The rendering layer can bind data through WXML.
    Sample Code
    <view>{{text}}</view>
    <view>{{array[0].msg}}</view>
    Page({
    data: {
    text: 'init data',
    array: [{msg: '1'}, {msg: '2'}]
    }
    })

    Lifecycle callback function

    The triggering of the lifecycle and the page routing method.

    onLoad(Object query)

    Triggered when the page is being loaded. A page will only call this once, and you can obtain the parameters in the current page path from the parameters in onLoad.
    Description:
    Name
    Type
    Description
    query
    object
    Parameters in the current page path.

    onShow()

    Triggered when the page is displayed or brought to the frontend.

    onReady()

    Triggered when the page is rendered for the first time. A page will only call this once, indicating that the page is ready and can interact with the view layer.
    Note:
    APIs that set interface content, such as wx.setNavigationBarTitle, should be executed after onReady. See Life Cycle for more details.

    onHide()

    Triggered when the page is hidden or moved to the backend, such as when navigateTo or the bottom tab switches to another page, or when the mini program moves to the backend.

    onUnload()

    Triggered when the page is being unloaded, such as when redirectTo or navigateBack to another page.

    Page event handling function

    onPullDownRefresh()

    Monitor user pull-to-refresh events.
    It is necessary to enable enablePullDownRefresh in the window option of app.json or in Page Configuration.
    You can trigger a pull-to-refresh by using wx.startPullDownRefresh. Upon invocation, it triggers a pull-to-refresh animation, producing an effect identical to a user-initiated pull-to-refresh.
    Upon completion of data refresh, wx.stopPullDownRefresh can stop the pull-to-refresh on the current page.

    onReachBottom()

    Monitor user events where a user pulls up and hits the bottom.
    You can set the trigger distance onReachBottomDistance in the window option of app.json or in Page Configuration.
    During the slide within the trigger distance, this event will only be activated once.

    onPageScroll(Object)

    Monitor events of users sliding the page.
    Explanation of the Object parameter:
    Attribute
    Type
    Description
    scrollTop
    number
    The distance the page has scrolled in the vertical direction (unit: px).
    Note:
    Please only define this method in the page when necessary, and avoid defining empty methods. This helps to minimize the impact of unnecessary event dispatch on the communication between the rendering layer and the logic layer.
    Please refrain from executing setData too frequently in onPageScroll, as it can cause communication between the logic layer and the rendering layer. Especially when transmitting large amounts of data, it can increase communication duration.

    onAddToFavorites(Object)

    Monitor the user's behavior of clicking the "favorite" button within the page (button component open-type="addToFavorites") or the "favorite" button in the top right corner menu, and customize the favorite content. The base library supports version 1.4.0 and later versions.
    Explanation of the Object parameter:
    Field
    Type
    Description
    fromw
    string
    Source of the forwarding event
    Button: The "forward" button within the page.
    Menu: The forwarding menu in the top right corner.
    webviewUrl
    string
    When the <web-view> component is included in the page, it returns the URL of the current <web-view>.
    An Object must be returned within the event handling function in order to customize the collection content. The required return content is as follows:
    Content of custom parameters
    Field
    Type
    Description
    Default value
    title
    string
    Parameter Title
    Current Mini Program Name
    imageUrl
    string
    Custom image path, which can be a local file path, code package file path, or network image path. Supports PNG and JPG formats.
    Current Mini Program Logo
    query
    string
    Page query parameters, such as a=1&b=2
    Current page's query parameters
    Sample Code
    Page({
    onAddToFavorites: function(res) {
    console.log('webviewUrl', res.webviewUrl);
    console.log('from', res.from);
    return {
    Title: 'Add to Favorites Title',
    imageUrl: '',
    query: 'a=1&b=2',
    }
    },
    })

    onShareAppMessage(Object)

    Monitor user behavior when clicking the top right menu options "Share with Friends" and "Share to Space", and customize the forwarded content.
    Note:
    Upon defining this event handling function, clicking the top right corner menu will display the "Share with Friends" and "Share to Space" buttons. There is no need to call showShareMenu, and hideShareMenu is ineffective.
    Explanation of the Object parameter:
    Field
    Type
    Description
    from
    string
    Source of the forwarding event. Button: Forwarding button within the page; Menu: Top right forwarding menu.
    target
    object
    If the value of 'from' is 'button', then 'target' is the button that triggered this forwarding event; otherwise, it is "undefined".
    webViewUrl
    string
    When the <web-view> component is included in the page, it returns the URL of the current <web-view>.
    shareTarget
    string
    For details on where the user clicks to share, see the explanation of the 'shareTarget' parameter below.
    An Object must be returned within the event handling function in order to customize the forwarding content. The return content is as follows:
    shareTarget parameter description
    Value
    Description
    0
    Share to QQ Friends
    1
    Share to QQ Space
    2
    Open from the current chat window for swift sharing to the same chat window.
    3
    Share to WeChat Friends
    4
    Share to WeChat Moments
    5
    Share via the panel to recent contacts.
    6
    Share to the Quick Share Friends List
    Customize the forwarding content
    Field
    Type
    Description
    Default value
    Earliest Version
    title
    string
    Forwarding Title
    Current Mini Program Name
    -
    path
    string
    Forwarding path
    The current page path must be a complete path starting with /.
    -
    imageUrl
    string
    Customize the image path, which can be a local file path, a code package file path, or a network image path. Both PNG and JPG formats are supported. The default share template displays an image aspect ratio of 5:4.
    Use Default Screenshot
    -
    shareType
    string
    Specify the type of sharing. For details, see the shareType description below for details.
    "miniapp"
    1.4.0
    shareType
    This is used to specify the type of sharing. Currently, there are two types of sharing: one is sharing a mini program, and the other is sharing an image.
    Value
    Description
    "miniapp"
    When sharing in the form of a mini program, the parameters title, path, imageUrl, generalWebpageUrl, entryDataHash, shareTemplateId, and shareTemplateData will take effect.
    "picture"
    When sharing in the form of an image, the parameters imageUrl and entryDataHash will take effect.
    Sample Code
    Page({
    onShareAppMessage(res) {
    if (res.from === 'button') {
    // From the page's share button
    console.log(res.target)
    }
    return {
    title: 'Custom Forwarding Title',
    path: '/page/user?id=123'
    }
    }
    })

    onResize(object)

    Triggered when the mini program screen rotates. For more details, see Responding to Display Area Changes.

    onTabItemTap(Object)

    Triggered when the tab is clicked.
    Explanation of the Object parameter:
    Field
    Type
    Description
    index
    string
    The sequence number of the clicked tabItem, starting from 0.
    pagePath
    string
    The page path of the clicked tabItem.
    text
    string
    The button text of the clicked tabItem.
    Sample Code
    Page({
    onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
    }
    })

    Component event handling function

    Event handling functions can also be defined within the Page. By incorporating event binding into the rendering layer's components, the event handling functions defined in the Page will be executed when the event is triggered.
    Sample Code
    <view bindtap="viewTap">click me</view>
    Page({
    viewTap() {
    console.log('view tap')
    }
    })

    route

    Page.route

    The path to the current page, of type String.
    Page({
    onShow() {
    console.log(this.route)
    }
    })

    setData

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

    The setData function is used to transmit data from the logical layer to the view layer (asynchronously), while simultaneously altering the corresponding value of this.data (synchronously).

    Description

    Field
    Type
    Required
    Description
    data
    object
    Yes
    The data to be modified this time.
    callback
    function
    No
    Callback function executed after the interface update triggered by setData has been fully rendered.
    An Object represented in the form of key: value, changing the value corresponding to key in this.data to value.
    The key can be provided in the form of a data path, supporting the modification of an item in an array or an attribute of an object, such as array[2].message, a.b.c.d, and it is not necessary to predefine it in this.data.
    Note:
    Directly modifying this.data without calling this.setData will not change the page's status and may lead to data inconsistency.
    Only supports setting data that can be serialized into JSON.
    The data set in a single instance should not exceed 1,024 kB. Avoid setting excessive data at once.
    Please refrain from setting the value of any item in data to "undefined", as this will prevent the item from being set and may leave potential issues unresolved.
    Sample Code
    <!--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() {
    // this.data.text = 'changed data' // Do not directly modify this.data
    // SetData shall be used.
    this.setData({
    text: 'changed data'
    })
    },
    changeNum() {
    // Alternatively, you can modify this.data and immediately use setData to set the modified fields.
    this.data.num = 1
    this.setData({
    num: this.data.num
    })
    },
    changeItemInArray() {
    // For object or array fields, one can directly modify a subfield within them. This approach is typically more advantageous than modifying the entire object or array.
    this.setData({
    'array[0].text': 'changed data'
    })
    },
    changeItemInObject() {
    this.setData({
    'object.text': 'changed data'
    })
    },
    addNewField() {
    this.setData({
    'newField.text': 'new data'
    })
    }
    })

    Considerations for Using setData

    1. The workflow of setData
    The workflow of setData can be broadly divided into the following stages:
    Traversal and update of the virtual DOM tree in the logical layer, triggering component lifecycle and observers, among others.
    Transferring data from the logical layer to the view layer.
    Updating the virtual DOM tree in the view layer, updating the actual DOM elements, and triggering page rendering updates.
    2. Usage Recommendations
    2.1 Data should only include rendering-related information
    setData should only be used for rendering-related data updates. Updating fields unrelated to rendering using setData can trigger additional rendering processes, or increase the amount of data transferred, increasing rendering duration.
    The data field of a page or component should be used to store data related to the rendering of the page or component (i.e., fields that appear directly in the wxml).
    Data unrelated to the rendering of the page or component should be placed under fields other than data, such as this.userData = {userId: 'xxx'}.
    Avoid including non-rendering related business data in the data field.
    Avoid using data for data sharing between page or component methods.
    2.2 Control the frequency of setData
    Each setData invocation triggers a traversal and update of the virtual DOM tree in the logic layer, and may also trigger a complete page rendering process. Excessively frequent (millisecond-level) calls to setData can lead to the following consequences:
    The logic layer JS thread remains continuously busy, unable to properly respond to user operation events, nor can it complete page transitions normally.
    The view layer JS thread remains continuously occupied, leading to increased communication time from the logic layer to the view layer. The delay in receiving messages in the view layer is relatively high, resulting in noticeable rendering delays.
    The view layer cannot respond to user operations in a timely manner; users experience noticeable lag when scrolling the page; operation feedback is delayed; user operation events cannot be promptly passed to the logic layer; the logic layer is also unable to convey the operation processing results to the view layer in time.
    Hence, developers should be mindful when invoking setData:
    Invoke setData only when a page content update is necessary.
    Strive to consolidate consecutive setData invocations whenever possible.
    Avoid unnecessary setData invocations.
    Avoid invoking setData at an excessively high frequency, such as a millisecond-level countdown.
    Avoid invoking setData in every onPageScroll callback.
    2.3 setData should only transmit data that has changed
    The volume of setData can impact the time consumed in data copying and communication, increasing the overhead of page updates and causing delays in page refreshes.
    setData should only input fields that have changed.
    It is recommended to change a specific item in an array or a particular attribute of an object using the data path format, such as this.setData({'array[2].message': 'newVal', 'a.b.c.d': 'newVal'}), instead of updating the entire object or array each time.
    Do not lazily pass all data at once in setData: this.setData(this.data).
    2.4 Control the setData of the backend status page
    Since the logic layer of the mini program runs on a single thread, the setData operation in the backend status page can also seize the running resources of the frontend page. As users cannot perceive the rendering of the backend status page, this can lead to waste. On some platforms, each WebView of the mini program rendering layer also shares the same thread, so the rendering and logic execution of the backend page can cause the frontend page to stutter.
    Updates after the page switches to the backend should be avoided whenever possible, or delayed until after the page's onShow event.
    Avoid performing high-frequency setData operations after switching to the backend, such as countdown updates.

    Lifecycle

    The diagram below illustrates the lifecycle of a Page instance.
    
    
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support