[Micro] setData letter applet use and precautions

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

setDataFunction is used to transmit data from the logical layer to the view layer (asynchronous), while corresponding to the change this.datavalue (synchronization).

Parameter Description

Field Types of Mandatory description Minimum version
data Object Yes The data to be changed
callback Function no SetData interface due to update the callback function after rendering is completed 1.5.0

ObjectIn key: valuethe form represented, to this.datathe keychange to the value corresponding to value.

Which keycan be given as the data path, to support a property change in an array or an object, such as array[2].message, a.b.c.dand no need to define in the this.data.

note:

  1. This.data modified directly without calling this.setData can not change the state of the page, it will result in data inconsistency .
  2. Only supports setting of JSON data.
  3. A single data set can not exceed 1024kB, try to avoid too much of a set of data.
  4. Do not set the value data to any one undefined, or this one will not be set up and may be left behind some of the potential problems.

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: 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'
    })
  }
})

Guess you like

Origin www.cnblogs.com/ljl-zszy/p/11918245.html