How to Build a Shopping Cart with Vue.js and Firebase

In this tutorial, we will walk through the process of building a shopping cart using Vue.js and Firebase. Firebase is a powerful backend-as-a-service platform that provides a real-time database and authentication for our application. We will utilize the real-time nature of Firebase to create a dynamic shopping cart that updates in real-time as items are added or removed.

Here’s what we will cover in this tutorial:

  1. Setting up Firebase project
  2. Creating the Vue.js project
  3. Designing the shopping cart
  4. Implementing the shopping cart functionality
  5. Connecting the shopping cart to Firebase
  6. Testing the shopping cart
  7. Conclusion

Let’s get started!

1. Setting up Firebase project

To use Firebase in our project, we first need to create a new Firebase project. Follow these steps to set up your Firebase project:

  1. Go to the Firebase Console and create a new project.
  2. In the project settings, navigate to the “General” tab and click on “Add Firebase to your web app”.
  3. Copy the provided configuration object, as we will need it later in our Vue.js application.

2. Creating the Vue.js project

Next, we need to set up a new Vue.js project using the Vue CLI. If you haven’t already installed the Vue CLI, you can install it globally using the following command:

$ npm install -g @vue/cli

Once the Vue CLI is installed, create a new Vue.js project using the following command:

$ vue create shopping-cart

Follow the prompts to select the options for your project. Once the project is created, navigate into the project directory:

$ cd shopping-cart

Now, you can run the project locally using the following command:

$ npm run serve

Your Vue.js project should now be running locally and accessible at `http://localhost:8080/`.

3. Designing the shopping cart

Before we start implementing the shopping cart functionality, let’s design the user interface for our shopping cart. Create a new file called Cart.vue in the src/components directory and add the following code:

<template>
  <div class="cart">
    <h2>Your Shopping Cart</h2>
    <div v-if="items.length === 0" class="empty-cart">
      Your cart is empty.
    </div>
    <div v-else>
      <div v-for="item in items" :key="item.id" class="cart-item">
        <div class="item-info">
          <h3>{{ item.name }}</h3>
          <p>Price: {{ item.price }}</p>
          <p>Quantity: {{ item.quantity }}</p>
        </div>
        <button @click="removeItem(item.id)">Remove</button>
      </div>
      <div class="total">
        <h3>Total: {{ total }}</h3>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: []
    };
  },
  computed: {
    total() {
      return this.items.reduce((acc, item) => acc + item.price * item.quantity, 0);
    }
  },
  methods: {
    removeItem(itemId) {
      // Implement code to remove item from cart
    }
  }
};
</script>

<style scoped>
/* Add your own styles here */
</style>

This code defines the structure and layout of our shopping cart component. It uses Vue.js directives (v-if, v-else, v-for) to conditionally render the content based on the state of the shopping cart.

4. Implementing the shopping cart functionality

Now, let’s implement the shopping cart functionality in Vue.js. Open the App.vue file in the src directory and update the template code to include the Cart component:

<template>
  <div id="app">
    <h1>Vue.js Shopping Cart</h1>
    <div class="product-list">
      <!-- Render product list -->
    </div>
    <Cart />
  </div>
</template>

Next, we need to define the product list in the data object:

data() {
  return {
    products: [
      {
        id: 1,
        name: "Product 1",
        price: 10
      },
      {
        id: 2,
        name: "Product 2",
        price: 15
      },
      {
        id: 3,
        name: "Product 3",
        price: 20
      }
    ]
  };
}

We also need to import the Cart component in the App.vue file:

import Cart from "@/components/Cart.vue";

export default {
  components: {
    Cart
  },
  // Rest of the code
};

At this point, our shopping cart component is ready for implementation.

5. Connecting the shopping cart to Firebase

To connect the shopping cart to Firebase, we will use the Firebase Realtime Database to store and retrieve the cart items in real-time.

First, install the Firebase module using the following command:

$ npm install firebase

Create a new file called firebase.js in the src directory and add the following code:

import firebase from "firebase/app";
import "firebase/database";

// Your Firebase configuration
const firebaseConfig = {
  // Add your project configuration here
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Export the Firebase database module
export default firebase.database();

Replace the firebaseConfig object with the configuration object you copied from the Firebase console earlier.

Now, we can use the Firebase database module to retrieve and update the shopping cart items.

Update the Cart.vue component with the following code:

<script>
import db from "../firebase";

export default {
  data() {
    return {
      items: []
    };
  },
  computed: {
    total() {
      return this.items.reduce((acc, item) => acc + item.price * item.quantity, 0);
    }
  },
  methods: {
    removeItem(itemId) {
      const index = this.items.findIndex(item => item.id === itemId);
      if (index !== -1) {
        this.items.splice(index, 1);
        db.ref("cart").set(this.items);
      }
    }
  },
  created() {
    db.ref("cart").on("value", snapshot => {
      this.items = snapshot.val() || [];
    });
  }
};
</script>

The created lifecycle hook is used to listen for changes in the Firebase database and update the items array accordingly. The removeItem method is used to remove an item from the cart and update the Firebase database.

6. Testing the shopping cart

To test the shopping cart functionality, let’s add a button to add products to the cart in the ProductList component.

Open the App.vue file and update the template code to include the product list and add the button:

<template>
  <div id="app">
    <h1>Vue.js Shopping Cart</h1>
    <div class="product-list">
      <div v-for="product in products" :key="product.id" class="product">
        <h3>{{ product.name }}</h3>
        <p>Price: {{ product.price }}</p>
        <button @click="addItem(product.id)">Add to Cart</button>
      </div>
    </div>
    <Cart />
  </div>
</template>

Add the addItem method to the App.vue component:

methods: {
  addItem(productId) {
    const product = this.products.find(product => product.id === productId);
    if (product) {
      const item = {
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: 1
      };
      db.ref("cart").push(item);
    }
  }
}

This method retrieves the selected product from the products array, creates a new item object with the required properties, and pushes it to the Firebase database.

Now, when you click the “Add to Cart” button, the item will be added to the cart and reflected in the shopping cart component.

7. Conclusion

In this tutorial, we have learned how to build a shopping cart using Vue.js and Firebase. We set up a new Firebase project, created a Vue.js project, designed the shopping cart component, implemented the shopping cart functionality, connected the shopping cart to Firebase, and tested the shopping cart.

You can further enhance the shopping cart by adding features like updating the quantity of items, implementing user authentication, and integrating with a payment gateway. Feel free to customize and expand on the code to meet the specific requirements of your application.

You can find the complete source code for this tutorial on GitHub.

Related Post