cart.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. Page({
  2. data:{
  3. cartList: [
  4. { id: 1, name: "商品A", price: 100, checked: false, count: 1 },
  5. { id: 2, name: "商品B", price: 200, checked: false, count: 2 },
  6. { id: 3, name: "商品C", price: 300, checked: false, count: 1 }
  7. ],
  8. isAllChecked: false, // 全选状态
  9. totalPrice:0,
  10. checkedCount:0
  11. },
  12. // 复选框变化事件
  13. handleCheckboxChange(e) {
  14. const checkedIds = e.detail.value; // 选中的商品id数组(如 ['1', '2'])
  15. const cartList = this.data.cartList.map(item => {
  16. item.checked = checkedIds.includes(item.id.toString());
  17. return item;
  18. });
  19. this.setData({
  20. cartList,
  21. isAllChecked: checkedIds.length === this.data.cartList.length
  22. });
  23. this.calculateTotal(); // 计算总价
  24. },
  25. // 全选/取消全选
  26. toggleAll() {
  27. const isAllChecked = !this.data.isAllChecked;
  28. const cartList = this.data.cartList.map(item => {
  29. item.checked = isAllChecked;
  30. return item;
  31. });
  32. this.setData({ cartList, isAllChecked });
  33. this.calculateTotal();
  34. },
  35. // 增加数量
  36. increaseCount(e) {
  37. const id = e.currentTarget.dataset.id;
  38. const cartList = this.data.cartList.map(item => {
  39. if (item.id == id) item.count++;
  40. return item;
  41. });
  42. this.setData({ cartList });
  43. this.calculateTotal();
  44. },
  45. // 减少数量
  46. decreaseCount(e) {
  47. const id = e.currentTarget.dataset.id;
  48. const cartList = this.data.cartList.map(item => {
  49. if (item.id == id && item.count > 1) item.count--;
  50. return item;
  51. });
  52. this.setData({ cartList });
  53. this.calculateTotal();
  54. },
  55. // 计算总价和选中数量
  56. calculateTotal() {
  57. let totalPrice = 0;
  58. let checkedCount = 0;
  59. this.data.cartList.forEach(item => {
  60. if (item.checked) {
  61. totalPrice += item.price * item.count;
  62. checkedCount++;
  63. }
  64. });
  65. this.setData({ totalPrice, checkedCount });
  66. }
  67. })