cart.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // 获取应用实例
  2. const {API} = require('../../service/api.js');
  3. Page({
  4. data:{
  5. cartList: [
  6. { id: 1, name: "商品A商品A商品A商品A商品A", price: 100, checked: false, count: 1 },
  7. { id: 2, name: "商品B商品B商品B商品B商品B", price: 200, checked: false, count: 2 },
  8. { id: 3, name: "商品C", price: 300, checked: false, count: 1 }
  9. ],
  10. isAllChecked: false, // 全选状态
  11. totalPrice:0,
  12. checkedCount:0,
  13. isManage:false, // 是否进入管理模式
  14. },
  15. // 获取购物车商品
  16. getCartProds(){
  17. API.getCartProds().then(res=>{
  18. console.log("999999999999",res);
  19. })
  20. },
  21. // 复选框变化事件
  22. handleCheckboxChange(e) {
  23. const checkedIds = e.detail.value; // 选中的商品id数组(如 ['1', '2'])
  24. const cartList = this.data.cartList.map(item => {
  25. item.checked = checkedIds.includes(item.id.toString());
  26. return item;
  27. });
  28. this.setData({
  29. cartList,
  30. isAllChecked: checkedIds.length === this.data.cartList.length
  31. });
  32. this.calculateTotal(); // 计算总价
  33. },
  34. // 全选/取消全选
  35. toggleAll() {
  36. const isAllChecked = !this.data.isAllChecked;
  37. const cartList = this.data.cartList.map(item => {
  38. item.checked = isAllChecked;
  39. return item;
  40. });
  41. this.setData({ cartList, isAllChecked });
  42. this.calculateTotal();
  43. },
  44. // 增加数量
  45. increaseCount(e) {
  46. const id = e.currentTarget.dataset.id;
  47. const cartList = this.data.cartList.map(item => {
  48. if (item.id == id) item.count++;
  49. return item;
  50. });
  51. this.setData({ cartList });
  52. this.calculateTotal();
  53. },
  54. // 减少数量
  55. decreaseCount(e) {
  56. const id = e.currentTarget.dataset.id;
  57. const cartList = this.data.cartList.map(item => {
  58. if (item.id == id && item.count > 1) item.count--;
  59. return item;
  60. });
  61. this.setData({ cartList });
  62. this.calculateTotal();
  63. },
  64. // 计算总价和选中数量
  65. calculateTotal() {
  66. let totalPrice = 0;
  67. let checkedCount = 0;
  68. this.data.cartList.forEach(item => {
  69. if (item.checked) {
  70. totalPrice += item.price * item.count;
  71. checkedCount++;
  72. }
  73. });
  74. this.setData({ totalPrice, checkedCount });
  75. },
  76. // 管理按钮
  77. manageBut(){
  78. this.setData({
  79. isManage:!this.data.isManage
  80. })
  81. },
  82. onLoad(){
  83. this.getCartProds();
  84. }
  85. })