07-WeChat Mini Program-Registration Page-Modularization

07-WeChat Mini Program-Registration Page

registration page

jsFor each page in the applet, it needs to be registered in the file corresponding to the page , specifying the initial data of the page, life cycle callback, event processing function, etc.

Register pages using the Page constructor

Simple pages can Page()be constructed using .

The Page(Object) function is used to register a page. It accepts a parameter of Object type, which specifies the initial data of the page, life cycle callback, event processing function, etc.

Parameter Object

Attributes type Defaults required illustrate
data Object The initial data of the page
options Object The component options of the page, the same as those in Componentthe constructoroptions , require the base library version 2.10.1
behaviors String Array Code reuse mechanism between components similar to mixins and traits, see behaviors , requires base library version 2.9.2
onLoad function Lifecycle callbacks - monitor page loads
onShow function Life cycle callback - monitor page display
onReady function Life cycle callback - monitor the completion of the initial rendering of the page
onHide function Life cycle callback - monitor page hidden
onUnload function Life cycle callback - monitor page unloading
onRouteDone function Life cycle callback - monitor route animation completion
onPullDownRefresh function Listen to the user's pull-down action
onReachBottom function Handling function of page bottoming event
onShareAppMessage function The user clicks on the upper right corner to repost
onShareTimeline function The user clicks on the upper right corner to forward to Moments
onAddToFavorites function The user clicks the favorite in the upper right corner
onPageScroll function Handling function for page scroll trigger event
onResize function Triggered when the page size changes, see Responding to Display Area Changes for details
onTabItemTap function When the current is a tab page, it is triggered when the tab is clicked
onSaveExitState function Preserve the state callback before the page is destroyed
other any Developers can add any function or data to Objectthe parameter, which can be accessed in the function of the page this. This part of properties will be deep copied once when the page instance is created .

Initial data

data is the initial data used for the first render of the page . When the page is loaded, data will be passed from the logic layer to the rendering layer in the form of JSON strings, so the data in data must be of a type that can be converted into JSON: strings, numbers, boolean values, objects, and arrays.

The rendering layer can WXMLbind data through .

case code

index.wxml

<view>{
   
   {text}}</view>
<view>{
   
   {array[0].msg}}</view>

index.js

  data: {
    
    
    "text":"hello",
    "array":[
      {
    
    
        "msg":"wold"
      }
    ]
  },
  • Effect

insert image description here

Lifecycle callback function

The triggering of the life cycle and the routing method of the page are detailed in

parameter:

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

illustrate:

function illustrate
onLoad(Object query) Fired when the page loads. A page will only be called once, and the parameters in the path to open the current page can be obtained from the parameters of onLoad.
onShow() Triggered when the page is displayed/cut to the foreground.
onReady() Fired when the page's initial rendering is complete. A page will only be called once, which means that the page is ready to interact with the view layer.
onHide() Triggered when the page hides/cuts to the background. Such as wx.navigateTo or tabswitch to other pages at the bottom, and the applet cuts into the background, etc.
onUnload() Fired when the page is unloaded. Such as wx.redirectTo or wx.navigateBack to other pages.
onRouteDone() Fired when the routing animation completes. For example, when the wx.navigateTo page is fully pushed or the wx.navigateBack page is fully restored

Note: APIs for setting interface content, such as wx.setNavigationBarTitle , should be onReadyperformed later. See life cycle for details

index.jsA lot has been generated directly, let's print a log now

// pages/demo/index.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    "text":"hello",
    "array":[
      {
    
    
        "msg":"wold"
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(options) {
    
    
    console.log("页面加载完成",options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady:function() {
    
    
    console.log("页面准备完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:function() {
    
    
    console.log("页面显示");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide:function() {
    
    
    console.log("页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload:function () {
    
    
    console.log("页面卸载");  

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh:function() {
    
    
    console.log("页面下拉");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom:function() {
    
    
    console.log("页面上拉触底事件");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage:function() {
    
    
    console.log("用户分享页面");
  }
})
  • Effect

insert image description here

insert image description here

Component event handler

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

index.wxml

<!--绑定点击事件-->
<view bindtap="viewTap">click me</view>

index.js

Page({
    
    
viewTap() {
    
    
console.log('view tap')
}
})

insert image description here

setData()

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

setDataFunctions are used to send data from the logic layer to the view layer (asynchronous) and change this.datathe value of the corresponding (synchronous).

  • Parameter Description
field type required describe minimum version
data Object yes The data to be changed this time
callback Function no The callback function after the rendering of the interface update caused by setData 1.5.0

ObjectExpressed in key: valuethe form of , change the corresponding value of this.datain to .keyvalue

Among them key, can be given in the form of data path, which supports changing an item in the array or a certain attribute of the object, such as array[2].message, a.b.c.d, and does not need to be this.data pre-defined in .

Notice:

  1. Direct modification this.datawithout calling this.setDatacannot change the state of the page, and will also cause data inconsistency .
  2. Only JSONdata that can be set is supported.
  3. The data set at one time cannot exceed 1024kB, please try to avoid setting too much data at one time.
  4. Please do not set the value of any item in data undefined, otherwise this item will not be set and may leave some potential problems.

case 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

// pages/demo/index.js
Page({
    
    
  changeText() {
    
    
    // this.data.text = 'changed data' // 不要直接修改 this.data
    // 应该使用 setData
    this.setData({
    
    
    text: 'changed data'
    })
    },
    changeNum() {
    
    
    // 或者,可以修改 this.data 之后马上用 setData 设置一下修改了的字段
    this.data.num = 1
    this.setData({
    
    
    num: this.data.num
    })
    },
    changeItemInArray() {
    
    
      // 对于对象或数组字段,可以直接修改一个其下的子字段,这样做通常比修改整个对象或数组更好
      this.setData({
    
    
      'array[0].text': 'changed data'
      })
      },
      changeItemInObject() {
    
    
      this.setData({
    
    
      'object.text': 'changed data'
      })
      },
      addNewField() {
    
    
      this.setData({
    
    
      'newField.text': 'new data'
      })
      },
    
  /**
   * 页面的初始数据
   */
  data: {
    
    
    text: 'init data',
    num: 0,
    array: [{
    
     text: 'init data' }],
    object: {
    
    
    text: 'init data'
    }
  },
    

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(options) {
    
    
    console.log("页面加载完成",options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady:function() {
    
    
    console.log("页面准备完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:function() {
    
    
    console.log("页面显示");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide:function() {
    
    
    console.log("页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload:function () {
    
    
    console.log("页面卸载");  

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh:function() {
    
    
    console.log("页面下拉");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom:function() {
    
    
    console.log("页面上拉触底事件");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage:function() {
    
    
    console.log("用户分享页面");
  }
})
  • Effect
setDate ![Insert picture description here](https://img-blog.csdnimg.cn/732cba7a9150457a9adce66ce834a8c5.gif#pic_center)

life cycle

You don't need to fully understand what follows right away, but it will help later.

The following diagram illustrates Pagethe lifecycle of a page instance.

insert image description here

Modular

Some common code can be extracted into a separate js file as a module. Only through module.exportsor exportscan the module expose the interface externally.

Notice:

  • exportsIt is module.exportsa reference of , so changing the pointing of at random in the module exportswill cause unknown errors. Therefore, it is recommended that developers use module.exportsto expose module interfaces, unless you already know the relationship between the two.
  • Mini Programs currently do not support direct import node_modules. Developers are advised node_modulesto copy relevant codes to the Mini Program directory, or use the npm function supported by Mini Programs.
// common.js
function sayHello(name) {
    
    
  console.log(`Hello ${
      
      name} !`)
}
function sayGoodbye(name) {
    
    
  console.log(`Goodbye ${
      
      name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

In files that need to use these modules, requireimport the common code using

var common = require('common.js')
Page({
    
    
  helloMINA: function() {
    
    
    common.sayHello('张小小')
  },
  goodbyeMINA: function() {
    
    
    common.sayGoodbye('张小小')
  }
})

insert image description here
Next Chapter WeChat Mini Program - View Layer

Guess you like

Origin blog.csdn.net/u014096024/article/details/132371855