addCartModel.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // components/addCartModel/addCartModel.js
  2. Component({
  3. properties: {
  4. visible: {
  5. type: Boolean,
  6. value: false
  7. },
  8. product: {
  9. type: Object,
  10. value: {}
  11. }
  12. },
  13. data: {
  14. selectedSpecs: [], // 选择的规格索引 [0,1]表示第一个规格的第0个选项,第二个规格的第1个选项
  15. quantity: 1
  16. },
  17. observers: {
  18. 'product': function(specs) {
  19. console.log("888888888888",specs);
  20. }
  21. },
  22. methods: {
  23. handleClose() {
  24. this.triggerEvent('close');
  25. },
  26. selectSpec(e) {
  27. const { specIndex, optionIndex } = e.currentTarget.dataset;
  28. const { selectedSpecs } = this.data;
  29. selectedSpecs[specIndex] = optionIndex;
  30. this.setData({ selectedSpecs });
  31. },
  32. isSpecSelected(specIndex, optionIndex) {
  33. return this.data.selectedSpecs[specIndex] === optionIndex;
  34. },
  35. increaseQuantity() {
  36. const { quantity, product } = this.data;
  37. if (quantity < product.stock) {
  38. this.setData({ quantity: quantity + 1 });
  39. }
  40. },
  41. decreaseQuantity() {
  42. const { quantity } = this.data;
  43. if (quantity > 1) {
  44. this.setData({ quantity: quantity - 1 });
  45. }
  46. },
  47. handleAddToCart() {
  48. const { product, selectedSpecs, quantity } = this.data;
  49. // 获取选中的规格文本
  50. const selectedSpecText = product.specs.map((spec, index) => {
  51. return spec.options[selectedSpecs[index]];
  52. }).join(',');
  53. // 组装添加到购物车的数据
  54. const cartItem = {
  55. productId: product.id,
  56. image: product.image,
  57. name: product.name,
  58. price: product.price,
  59. quantity,
  60. selectedSpecs: selectedSpecText,
  61. stock: product.stock
  62. };
  63. this.triggerEvent('add', { item: cartItem });
  64. }
  65. },
  66. computed: {
  67. selectedSpecText() {
  68. const { product, selectedSpecs } = this.data;
  69. if (!product.specs || product.specs.length === 0) return '';
  70. return product.specs.map((spec, index) => {
  71. return spec.options[selectedSpecs[index]];
  72. }).join(',');
  73. }
  74. }
  75. });