12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- const state = {
- cart: [],
- total: 0
- }
- const getters = {
- getCartItems(state) {
- return state.cart
- },
- getTotal(state) {
- return state.total
- },
- cartIsEmpty(state) {
- return state.cart.length !== 0
- }
- }
- const mutations = {
- addToCart(state, payload) {
- let finded = state.cart.find(item => item.id == payload.product.id)
- if (finded) {
- payload.product.qty = payload.product.qty + 1
- } else {
- state.cart = [payload.product, ...state.cart]
- }
- },
- calculateTotal(state) {
- let sum = 0
- state.cart.forEach(item => {
- sum = sum + (item.list_price * (item.qty || 1))
- })
- state.total = sum
- }
- }
- const actions = {
- addToCart({ commit, dispatch }, payload) {
- commit('addToCart', payload)
- commit('calculateTotal')
- dispatch('setSelectedProduct', {
- product: null
- })
- }
- }
- export default {
- state,
- getters,
- mutations,
- actions
- }
|