ZJCF_miniProgram/pages/shop/buycar/buycar.js

107 lines
3.4 KiB
JavaScript
Raw Normal View History

2024-12-07 10:20:50 +08:00
Page({
data: {
cartItems: [
{ id: 1, name: '商品A', price: 100, quantity: 1, image: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner1.png', selected: false },
{ id: 2, name: '商品B', price: 200, quantity: 1, image: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner2.png', selected: false },
{ id: 3, name: '商品C', price: 300, quantity: 1, image: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner3.png', selected: false },
{ id: 4, name: '商品D', price: 400, quantity: 1, image: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner4.png', selected: false },
{ id: 5, name: '商品E', price: 500, quantity: 1, image: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner5.png', selected: false }
],
total: 0,
total_goods: 0,
allSelected: false
},
onLoad: function() {
this.calculateTotal();
this.calculateTotal_goods();
},
toggleSelection: function(e) {
const id = e.currentTarget.dataset.id;
const index = this.data.cartItems.findIndex(item => item.id === id);
if (index !== -1) {
let updatedItem = this.data.cartItems[index];
updatedItem.selected = !updatedItem.selected;
this.setData({
['cartItems[' + index + ']']: updatedItem
});
this.calculateTotal();
this.calculateTotal_goods();
this.updateAllSelected();
}
},
toggleAllSelection: function() {
const newSelection = !this.data.allSelected;
const updatedCartItems = this.data.cartItems.map(item => ({
...item,
selected: newSelection
}));
this.setData({
cartItems: updatedCartItems,
allSelected: newSelection
});
this.calculateTotal();
this.calculateTotal_goods();
},
increaseQuantity: function(e) {
const id = e.currentTarget.dataset.id;
const index = this.data.cartItems.findIndex(item => item.id === id);
if (index !== -1) {
let updatedItem = this.data.cartItems[index];
updatedItem.quantity += 1;
this.setData({
['cartItems[' + index + ']']: updatedItem
});
this.calculateTotal();
}
},
decreaseQuantity: function(e) {
const id = e.currentTarget.dataset.id;
const index = this.data.cartItems.findIndex(item => item.id === id);
if (index !== -1) {
let updatedItem = this.data.cartItems[index];
if (updatedItem.quantity > 1) {
updatedItem.quantity -= 1;
this.setData({
['cartItems[' + index + ']']: updatedItem
});
this.calculateTotal();
}
}
},
calculateTotal: function() {
let total = 0;
this.data.cartItems.forEach(item => {
if (item.selected) {
total += item.price * item.quantity;
}
});
this.setData({ total: total });
},
calculateTotal_goods: function() {
let total_goods = this.data.cartItems.reduce((acc, item) => {
return acc + (item.selected ? 1 : 0);
}, 0);
this.setData({ total_goods: total_goods });
},
updateAllSelected: function() {
const allSelected = this.data.cartItems.every(item => item.selected);
this.setData({ allSelected: allSelected });
},
checkout: function() {
wx.showToast({
title: '结算成功',
icon: 'success',
duration: 2000
});
}
});