cart.js 946 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const state = {
  2. cart: [],
  3. total: 0
  4. }
  5. const getters = {
  6. getCartItems(state) {
  7. return state.cart
  8. },
  9. getTotal(state) {
  10. return state.total
  11. },
  12. isEmpty(state) {
  13. return state.cart.length !== 0
  14. }
  15. }
  16. const mutations = {
  17. addToCart(state, payload) {
  18. let finded = state.cart.find(item => item.id == payload.product.id)
  19. if (finded) {
  20. payload.product.qty = payload.product.qty + 1
  21. } else {
  22. state.cart = [payload.product, ...state.cart]
  23. }
  24. },
  25. calculateTotal(state) {
  26. let sum = 0
  27. state.cart.forEach(item => {
  28. sum = sum + (item.list_price * (item.qty || 1))
  29. })
  30. state.total = sum
  31. }
  32. }
  33. const actions = {
  34. addToCart({ commit }, payload) {
  35. commit('addToCart', payload)
  36. commit('calculateTotal')
  37. }
  38. }
  39. export default {
  40. state,
  41. getters,
  42. mutations,
  43. actions
  44. }