From 73751eff7688ec9994c098ba95f1c08fad210e31 Mon Sep 17 00:00:00 2001 From: Mateja Date: Sun, 25 Jul 2021 16:31:16 +0200 Subject: Product page shows amount of product in cart. Allows for removal of product from cart. Product page now uses Vuex instead of local values. --- client/src/store/index.js | 41 +++++++++++++++++++++++++++++++----- client/src/views/Product.vue | 49 +++++++++++++++++++++----------------------- 2 files changed, 59 insertions(+), 31 deletions(-) (limited to 'client') diff --git a/client/src/store/index.js b/client/src/store/index.js index 3d612c7..086c544 100644 --- a/client/src/store/index.js +++ b/client/src/store/index.js @@ -4,6 +4,7 @@ import axios from 'axios'; export default createStore({ state: { products: [], + currentProduct: {}, cart: [] }, getters: { @@ -22,23 +23,48 @@ export default createStore({ let sum = 0; state.cart.forEach(x => sum += x.price * x.quantity); return sum; + }, + getCurrentProduct(state) { + return state.currentProduct; + }, + getCurrentProductImgUrl(state) { + return `${process.env.VUE_APP_ROOT_API}/${state.currentProduct.imagePath}`; + }, + getCurrentProductQuantity(state) { + let amount = 0 + state.cart.forEach(x => { + if (x.id == state.currentProduct._id) + amount = x.quantity; + }); + return amount; } }, mutations: { setProducts(state, products) { state.products = products; }, - addToCart(state, product) { - let foundProduct = state.cart.find(x => x.id == product._id); + setCurrentProduct(state, product) { + state.currentProduct = product; + }, + addToCart(state) { + let foundProduct = state.cart.find(x => x.id == state.currentProduct._id); if (foundProduct) foundProduct.quantity++; else state.cart.push({ - id: product._id, - name: product.name, - price: product.price, + id: state.currentProduct._id, + name: state.currentProduct.name, + price: state.currentProduct.price, quantity: 1 }); + }, + removeFromCart(state) { + let foundProduct = state.cart.find(x => x.id == state.currentProduct._id); + if (foundProduct) { + foundProduct.quantity--; + if (foundProduct.quantity == 0) + state.cart = state.cart.filter(x => x.id != foundProduct.id); + } } }, actions: { @@ -46,6 +72,11 @@ export default createStore({ await axios.get(`${process.env.VUE_APP_ROOT_API}/products`) .then(response => context.commit('setProducts', response.data)) .catch(error => console.error(error)); + }, + async pullProduct(context, productId) { + await axios.get(`${process.env.VUE_APP_ROOT_API}/products/${productId}`) + .then(response => context.commit('setCurrentProduct', response.data)) + .catch(error => console.error(error)); } }, modules: { diff --git a/client/src/views/Product.vue b/client/src/views/Product.vue index 11643c1..ff43857 100644 --- a/client/src/views/Product.vue +++ b/client/src/views/Product.vue @@ -4,15 +4,19 @@
- +
-

- Price: ${{ productPrice }}
-

+

+
Price: ${{ curProduct.price }}
+

+

Amount: {{curProductQuantity}}

+
+
@@ -22,35 +26,28 @@