当前位置:主页 > >

微信小程序this.setData()动态修改数组中的某一值

时间:2019-11-19 14:45:23 | 栏目: | 点击:

我们需要动态修改数组中的某一个值时怎么办,可以拼装变量来进行赋值,请看例子。

add:function(e){
    let id = e.currentTarget.dataset.id // 获取传入的id
    let index = e.currentTarget.dataset.index  // 获取数据的索引
    let temp = 'goodsList[' + index +'].num'  // 获取goodsList[index].num
    this.setData({
      [temp]:this.data.goodsList[index].num + 1
    })
  }

goodsList为数组列表

data:{
  goodsList: [
    {
      _id:1,
      title: "澳洲原切牛排",
      desc: "一场精致的烛光晚餐从它开始",
      price: "8.00",
      imgUrl: "../../static/images/rou.png",
      num:0      // 需要改变的数据
    }, {
      _id:2,
      title: "安吉散养土鸡蛋",
      desc: "鲜嫩的口味,把田园的清新带给你",
      price: "8.00",
      imgUrl: "../../static/images/dan.png",
      num: 1      // 需要改变的数据
    }
  ]
}
关键就是拼装temp变量,利用[temp]来赋值。

您可能感兴趣的文章:

相关文章