WeChat applet setData modify the value of an item in the array

Examples of official documents:

changeItemInArray: function() {
    // 对于对象或数组字段,可以直接修改一个其下的子字段,这样做通常比修改整个对象或数组更好
    this.setData({
      'array[0].text':'changed data'
    })
  },

This method is effective for static data settings, but for dynamic data, it does not work and will report errors.

Solution: When setting the data, the key needs to be enclosed in square brackets ([])

I searched the Internet and recorded it here

wxml:

<block wx:for="{{list}}" wx:key="index">
    <view class="item" data-index="{{index}}" bindtap="changeNum">
      <text>
        种类: {{item.title}} \n 价格: ¥{{item.price}}元 \n 数量: {{item.num}}
      </text>
    </view>
</block>

js:

Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [{
        title: '苹果',
        price: 6.89,
        num: 2
      },
      {
        title: '橘子',
        price: 5.68,
        num: 1
      },
      {
        title: '香蕉',
        price: 3.98,
        num: 1
      },
    ],
  },

  //动态的更改数组中的数据,key只需要用中括号括起来就变成变量
  changeNum(e){
    var index = e.currentTarget.dataset.index
    this.setData({
        ['list['+ index + '].num'] : 5
    })
    
    //静态的只能修改香蕉的数量
    // this.setData({
    //   'list[2].num': 3
    // })
  },
  
})

PS: The newline character '\ n' must be used in the text tag, and it cannot be recognized in the view

Published 21 original articles · won praise 1 · views 7809

Guess you like

Origin blog.csdn.net/eva_feng/article/details/105235791