我们先来看一下背景:

微信小程序 列表渲染,数组更新_按钮

这个是一个列表页面,需要实现的是,对应的商品数量可以修改的,那么也就是我点击上面的+

号的时候,数量依次递增
我们先来分析一下,这两行商品是通过数组渲染的,点击加号修改的数量,其实是修改的数组中的元素,并且我们还需要确定修改的数组的那一行的元素

我们来看列表代码:

<checkbox-group bindchange="checkboxChange">
<view wx:for="{{goodsList}}" wx:for_item="item" wx:key="index" class="goods_item">
<checkbox value="{{item.rowguid}}" style="position: relative;top: -45px;"></checkbox>
<image src="{{item.picurl}}" lazy-load="true" mode="heightFix" ></image>
<text class="goods_title">{{item.goodsname+"..."}}</text>
<text class="goods_ggxh">{{item.ggxhname}}</text>
<text class="goods_price">¥{{item.buyprice}}</text>
<view class="goods_addnum">
<button size="mini" data-index="{{index}}" bindtap="subBookNum">-</button>
<input class="ggxh_num_input" type="number" value="{{item.buynum}}"> {{item.buynum}} </input>
<button size="mini" data-index="{{index}}" bindtap="addBookNum">+</button>
</view>
</view>
</checkbox-group>

<button size="mini" data-index="{{index}}" bindtap="addBookNum">+</button>

这个是点击+号对应的按钮,增加一个属性data-index ="{{index}}"  这个是数组的行索引,当点击按钮的时候,我知道需要对数组那一行的元素进行 更新

对应的事件:addBookNum

addBookNum:function(e){
let index=e.currentTarget.dataset.index;
let buynum=this.data.goodsList[index].buynum;
let f = 'goodsList[' + index + '].buynum'
this.setData({
[f]:buynum+1
})
},

可以看出的是,当点击+号按钮的时候,首先是获取到当前点击行的索引,然后获取到数组中对应的元素,并获取到当前的数量,最后对数量进行更新

响应的点击-号,也是这样进行操作

代码:

subBookNum:function(e){
let index=e.currentTarget.dataset.index;
let buynum=this.data.goodsList[index].buynum;
let f = 'goodsList[' + index + '].buynum'
if(buynum>1){
this.setData({
[f]:buynum-1
})
}

},
addBookNum:function(e){
let index=e.currentTarget.dataset.index;
let buynum=this.data.goodsList[index].buynum;
let f = 'goodsList[' + index + '].buynum'
this.setData({
[f]:buynum+1
})
},

希望对你有所帮助