WeChat applet (learning 2) -- setData (page data refresh)

The WeChat applet provides the function setData to send data from the logic layer to the data layer.

Page.prototype.setData() setData Used to send data from the logic layer to the view layer, while changing the value of the corresponding this.data. Accept an object and change the value corresponding to the key in this.data to value in the form of key and value.

The first thing to note is:
1. Modifying this.data directly without calling this.setData will not change the state of the page, and it will also cause data inconsistency
2. The data set in a single setting cannot exceed 1024kB, please try to avoid too many settings at one time The data.
3. Do not call this.setData very frequently. For example, register an update function by yourself and call this.setData once per frame, which may cause the application to freeze.

An example is given below and explained later.

<!--pages/test.wxml-->
<text>{{count}}</text>
<button bindtap='clickCount' data-msg='click'>点击计数</button>
// pages/test.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    count: 0,
  },
 /**
   * 计数
   */
  clickCount(options) {
    console.log(options);

    this.setData({
      count: this.data.count + 1
    });
  }
})

write picture description here
Every time the count value is changed, it can be refreshed on the page. Simple and easy to understand.

We call the clickCount(options) function when we click, and print the options. What if we want to pass parameters to clickCount, we can use it like this:

<button bindtap='clickCount' data-msg='click'>点击计数</button>

data-(the type of parameter you want to pass) = "parameter", WeChat will help you encapsulate the data, pass the information you click, and some information of the page to the logic segment, see the figure below.
write picture description here
How the msg parameter is
write picture description here
used :

let count = options.target.dataset.msg;

That's it for the use of data.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324502596&siteId=291194637