index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. changeQty (state, { product, qty }) {
  35. let cartProduct = state.cart.find(prod => prod._id === product._id )
  36. cartProduct.quantity = qty
  37. state.cartLength = 0
  38. if (state.cart.length > 0) {
  39. state.cart.map(product => {
  40. state.cartLength += product.quantity
  41. })
  42. }
  43. let indexOfProduct = state.cart.indexOf(cartProduct)
  44. state.cart.splice(indexOfProduct, 1, cartProduct)
  45. },
  46. removeProduct (state, product) {
  47. state.cartLength -= product.quantity
  48. let indexOfProduct = state.cart.indexOf(product)
  49. state.cart.splice(indexOfProduct, 1)
  50. }
  51. }
  52. export const getters = {
  53. getCartLength (state) {
  54. return state.cartLength
  55. },
  56. getCart (state) {
  57. return state.cart
  58. },
  59. getCartTotalPrice (state) {
  60. let total = 0
  61. state.cart.map(product => {
  62. total += product.price * product.quantity
  63. })
  64. return total
  65. }
  66. }