微信小程序购物车多选全选
时间: 2023-12-14 08:32:31 浏览: 126
以下是微信小程序购物车多选全选的实现方法:
1. 在wxml文件中,使用checkbox组件实现多选和全选功能,使用bindchange事件监听checkbox的状态变化,使用wx:for循环渲染商品列表。
```html
<view wx:for="{{goodsList}}" wx:key="id">
<checkbox value="{{item.checked}}" bindchange="checkboxChange" data-id="{{item.id}}"></checkbox>
<view>{{item.name}}</view>
<view>{{item.price}}</view>
</view>
<checkbox value="{{allChecked}}" bindchange="checkboxAllChange"></checkbox>
<view>全选</view>
<button bindtap="deleteGoods">删除</button>
```
2. 在js文件中,定义goodsList数组存储商品列表,定义allChecked变量表示全选状态,定义selectedIds数组存储选中的商品id。
```javascript
Page({
data: {
goodsList: [
{ id: 1, name: '商品1', price: 10, checked: false },
{ id: 2, name: '商品2', price: 20, checked: false },
{ id: 3, name: '商品3', price: 30, checked: false }
],
allChecked: false,
selectedIds: []
},
// checkbox状态变化事件
checkboxChange: function(e) {
var id = e.currentTarget.dataset.id;
var checked = e.detail.value.length > 0;
var goodsList = this.data.goodsList;
for (var i = 0; i < goodsList.length; i++) {
if (goodsList[i].id == id) {
goodsList[i].checked = checked;
break;
}
}
this.setData({
goodsList: goodsList
});
this.updateSelectedIds();
},
// 全选状态变化事件
checkboxAllChange: function(e) {
var allChecked = e.detail.value.length > 0;
var goodsList = this.data.goodsList;
for (var i = 0; i < goodsList.length; i++) {
goodsList[i].checked = allChecked;
}
this.setData({
goodsList: goodsList,
allChecked: allChecked
});
this.updateSelectedIds();
},
// 更新选中的商品id
updateSelectedIds: function() {
var goodsList = this.data.goodsList;
var selectedIds = [];
for (var i = 0; i < goodsList.length; i++) {
if (goodsList[i].checked) {
selectedIds.push(goodsList[i].id);
}
}
this.setData({
selectedIds: selectedIds
});
},
// 删除选中的商品
deleteGoods: function() {
var selectedIds = this.data.selectedIds;
var goodsList = this.data.goodsList;
for (var i = goodsList.length - 1; i >= 0; i--) {
if (selectedIds.indexOf(goodsList[i].id) >= 0) {
goodsList.splice(i, 1);
}
}
this.setData({
goodsList: goodsList,
allChecked: false,
selectedIds: []
});
}
})
```
阅读全文