index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. export const state = () => ({
  2. cart: [],
  3. cartLength: 0,
  4. price: 0,
  5. shippingPrice:0,
  6. estimatedDelivery: ''
  7. })
  8. export const actions = {
  9. addProductToCart ({ state, commit }, product) {
  10. const cartProduct = state.cart.find(prod => prod._id === product._id)
  11. if (!cartProduct) {
  12. commit('pushProductToCart', product)
  13. } else {
  14. commit('incrementProductQty', cartProduct)
  15. }
  16. commit('incrementCartLength')
  17. }
  18. }
  19. export const mutations = {
  20. pushProductToCart (state, product) {
  21. product.quantity = 1
  22. state.cart.push(product)
  23. },
  24. incrementProductQty (state, product) {
  25. product.quantity++
  26. let indexOfProduct = state.cart.indexOf(product)
  27. state.cart.splice(indexOfProduct, 1, product)
  28. },
  29. incrementCartLength (state) {
  30. state.cartLength = 0
  31. if (state.cart.length > 0) {
  32. state.cart.map(product => {
  33. state.cartLength += product.quantity
  34. })
  35. }
  36. },
  37. changeQty (state, { product, qty }) {
  38. let cartProduct = state.cart.find(prod => prod._id === product._id )
  39. cartProduct.quantity = qty
  40. state.cartLength = 0
  41. if (state.cart.length > 0) {
  42. state.cart.map(product => {
  43. state.cartLength += product.quantity
  44. })
  45. }
  46. let indexOfProduct = state.cart.indexOf(cartProduct)
  47. state.cart.splice(indexOfProduct, 1, cartProduct)
  48. },
  49. removeProduct (state, product) {
  50. state.cartLength -= product.quantity
  51. let indexOfProduct = state.cart.indexOf(product)
  52. state.cart.splice(indexOfProduct, 1)
  53. },
  54. setShipping (state, { price, estimatedDelivery }) {
  55. state.price = price
  56. state.estimatedDelivery = estimatedDelivery
  57. }
  58. }
  59. export const getters = {
  60. getCartLength (state) {
  61. return state.cartLength
  62. },
  63. getCart (state) {
  64. return state.cart
  65. },
  66. getCartTotalPrice (state) {
  67. let total = 0
  68. state.cart.map(product => {
  69. total += product.price * product.quantity
  70. })
  71. return total
  72. },
  73. getCartTotalPriceWithShipping (state) {
  74. let total = 0
  75. state.cart.map(product => {
  76. total += product.price * product.quantity
  77. })
  78. return total + state.shippingPrice
  79. }
  80. }