Browse Source

Step 9: Communicating events exercise.

Frederic G. MARAND 4 years ago
parent
commit
deb0b5330b
2 changed files with 15 additions and 3 deletions
  1. 1 1
      index.html
  2. 14 2
      main.js

+ 1 - 1
index.html

@@ -13,7 +13,7 @@
       <p>Cart({{cart.length}})</p>
     </div>
 
-    <product :is-premium="isPremium" @add-to-cart="updateCart"></product>
+    <product :is-premium="isPremium" @add-to-cart="updateCart" @remove-from-cart="removeItem"></product>
   </div>
 
   <script src="./assets/js/vue.js"></script>

+ 14 - 2
main.js

@@ -42,6 +42,7 @@ const productTemplate = `<div class="product">
                 :disabled="!inStock"
                 :class="{ disabledButton: !inStock }"
         >Add to cart</button>
+        <button v-on:click="removeFromCart">Remove</button>
       </div>
     </div>
 `;
@@ -115,10 +116,14 @@ Vue.component("product", {
         }
     },
     methods: {
-        addToCart(mouseEvent) {
+        addToCart() {
             this.variants[this.selectedVariant].variantQuantity--;
             this.$emit("add-to-cart", this.variants[this.selectedVariant].variantId);
         },
+        removeFromCart() {
+            this.variants[this.selectedVariant].variantQuantity++;
+            this.$emit("remove-from-cart", this.variants[this.selectedVariant].variantId);
+        },
         updateImage(index) {
             this.selectedVariant = index;
         }
@@ -132,8 +137,15 @@ const app = new Vue({
         isPremium: false,
     },
     methods: {
+        removeItem(id) {
+            console.log("removeItem", id);
+            const index = this.cart.indexOf(id);
+            if (index > -1) {
+                this.cart.splice(index, 1);
+            }
+        },
         updateCart(id) {
-            console.log("uC", id);
+            console.log("updateCart", id);
             this.cart.push(id);
         }
     }