Skip to content

Commit

Permalink
adding products to the cart
Browse files Browse the repository at this point in the history
  • Loading branch information
hootlex committed Jan 24, 2018
1 parent f946998 commit e56d562
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/components/ProductList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
src="https://i.imgur.com/JfPpwOA.gif"
>
<ul v-else>
<li v-for="product in products">{{product.title}} - {{product.price}}</li>
<li v-for="product in products">
{{product.title}} - {{product.price}}
<button @click="addProductToCart(product)">Add to cart</button>
</li>
</ul>
</div>
</template>
Expand All @@ -25,6 +28,12 @@
}
},
methods: {
addProductToCart (product) {
this.$store.dispatch('addProductToCart', product)
}
},
created () {
this.loading = true
this.$store.dispatch('fetchProducts')
Expand Down
31 changes: 30 additions & 1 deletion src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ Vue.use(Vuex)

export default new Vuex.Store({
state: { // = data
products: []
products: [],
// {id, quantity}
cart: []
},

getters: { // = computed properties
Expand All @@ -24,13 +26,40 @@ export default new Vuex.Store({
resolve()
})
})
},

addProductToCart (context, product) {
if (product.inventory > 0) {
const cartItem = context.state.cart.find(item => item.id === product.id)
if (!cartItem) {
context.commit('pushProductToCart', product.id)
} else {
context.commit('incrementItemQuantity', cartItem)
}
context.commit('decrementProductInventory', product)
}
}
},

mutations: {
setProducts (state, products) {
// update products
state.products = products
},

pushProductToCart (state, productId) {
state.cart.push({
id: productId,
quantity: 1
})
},

incrementItemQuantity (state, cartItem) {
cartItem.quantity++
},

decrementProductInventory (state, product) {
product.inventory--
}
}
})
Expand Down

0 comments on commit e56d562

Please sign in to comment.