| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- // components/addCartModel/addCartModel.js
- Component({
- properties: {
- visible: {
- type: Boolean,
- value: false
- },
- product: {
- type: Object,
- value: {}
- }
- },
-
- data: {
- selectedSpecs: [], // 选择的规格索引 [0,1]表示第一个规格的第0个选项,第二个规格的第1个选项
- quantity: 1
- },
-
- observers: {
- 'product': function(specs) {
- console.log("888888888888",specs);
- }
- },
-
- methods: {
- handleClose() {
- this.triggerEvent('close');
- },
-
- selectSpec(e) {
- const { specIndex, optionIndex } = e.currentTarget.dataset;
- const { selectedSpecs } = this.data;
-
- selectedSpecs[specIndex] = optionIndex;
- this.setData({ selectedSpecs });
- },
-
- isSpecSelected(specIndex, optionIndex) {
- return this.data.selectedSpecs[specIndex] === optionIndex;
- },
-
- increaseQuantity() {
- const { quantity, product } = this.data;
- if (quantity < product.stock) {
- this.setData({ quantity: quantity + 1 });
- }
- },
-
- decreaseQuantity() {
- const { quantity } = this.data;
- if (quantity > 1) {
- this.setData({ quantity: quantity - 1 });
- }
- },
-
- handleAddToCart() {
- const { product, selectedSpecs, quantity } = this.data;
-
- // 获取选中的规格文本
- const selectedSpecText = product.specs.map((spec, index) => {
- return spec.options[selectedSpecs[index]];
- }).join(',');
-
- // 组装添加到购物车的数据
- const cartItem = {
- productId: product.id,
- image: product.image,
- name: product.name,
- price: product.price,
- quantity,
- selectedSpecs: selectedSpecText,
- stock: product.stock
- };
-
- this.triggerEvent('add', { item: cartItem });
- }
- },
-
- computed: {
- selectedSpecText() {
- const { product, selectedSpecs } = this.data;
- if (!product.specs || product.specs.length === 0) return '';
-
- return product.specs.map((spec, index) => {
- return spec.options[selectedSpecs[index]];
- }).join(',');
- }
- }
- });
|