index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. export const state = () => ({
  2. cart: [],
  3. cartLength: 0
  4. })
  5. export const actions = {
  6. addProductToCart ({ state, commit }, product) {
  7. const cartProduct = state.cart.find(prod => prod._id === product._id)
  8. if (!cartProduct) {
  9. commit('pushProductToCart', product)
  10. } else {
  11. commit('incrementProductQty', cartProduct)
  12. }
  13. commit('incrementCartLength')
  14. }
  15. }
  16. export const mutations = {
  17. pushProductToCart (state, product) {
  18. product.quantity = 1
  19. state.cart.push(product)
  20. },
  21. incrementProductQty (state, product) {
  22. product.quantity++
  23. let indexOfProduct = state.cart.indexOf(product)
  24. state.cart.splice(indexOfProduct, 1, product)
  25. },
  26. incrementCartLength (state) {
  27. state.cartLength = 0
  28. if (state.cart.length > 0) {
  29. state.cart.map(product => {
  30. state.cartLength += product.quantity
  31. })
  32. }
  33. }
  34. }
  35. export const getters = {
  36. getCartLength (state) {
  37. return state.cartLength
  38. },
  39. getCart (state) {
  40. return state.cart
  41. },
  42. getCartTotalPrice (state) {
  43. let total = 0
  44. state.cart.map(product => {
  45. total += product.price * product.quantity
  46. })
  47. return total
  48. }
  49. }