DeveloperBreeze

Javascript Programming Tutorials, Guides & Best Practices

Explore 93+ expertly crafted javascript tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Building a Custom E-commerce Platform with Laravel and Vue.js

Tutorial August 27, 2024
javascript php

Create a new file named index.js inside the store directory:

// resources/js/store/index.js
import { createStore } from 'vuex';

const store = createStore({
  state: {
    cart: [],
  },
  mutations: {
    addToCart(state, product) {
      const item = state.cart.find((item) => item.id === product.id);
      if (item) {
        item.quantity += 1;
      } else {
        state.cart.push({ ...product, quantity: 1 });
      }
    },
  },
  actions: {
    addToCart({ commit }, product) {
      commit('addToCart', product);
    },
  },
  getters: {
    cartItems(state) {
      return state.cart;
    },
    cartTotal(state) {
      return state.cart.reduce((total, item) => total + item.price * item.quantity, 0);
    },
  },
});

export default store;