Let’s add a Shopping Cart Feature in Vue.js for Our Ecommerce App
Tags: java, javascript, ecommerce, backend
Published: 2021-03-10 20:55:03


In this tutorial, we will learn how to display, update and delete shopping cart items in our demo e-commerce app

![](https://cdn-images-1.medium.com/max/3250/1*QJ7vQmjrfa3-VXmxotituw.png)

## Introduction

We are building an e-commerce app from scratch using Vue.js in the frontend and Java with Springboot for the backend. You can check out the first frontend tutorial of this series here

{% medium https://javascript.plainenglish.io/lets-create-vue-js-frontend-for-products-in-our-e-commerce-app-14cc8c3459c8 %}

We are building a shopping cart component for displaying and updating the cart items user has added to his cart.

{% youtube MgOJmWMSTuQ %}

We will use Vue.js to make a beautiful UI for the shopping cart.

## Demo of what we will implement

[You can play with the e-commerce app here](http://remotedevs.org:8000/)
{% youtube 9UrxGYsWNiY %}
You can find the complete code at [Github](https://github.com/webtutsplus/ecommerce-vuejs).

## Backend

Previously, we have built the backend of the shopping cart using Java and Springboot. You can find it here
{% medium https://medium.com/javarevisited/lets-develop-shopping-cart-for-ecommerce-app-8e57a9ab4868 %}

## Pre-requisites

 1. Knowledge of Vuejs

 2. [Visual Studio Code](https://code.visualstudio.com/) **— **open-source (Recommended)

 3. A good browser **— **(Chrome — recommended)

## API description Summery

Before jumping to coding the frontend part, we have to discuss the API which we will be using for the frontend. You can find the backend code [here](https://github.com/webtutsplus/ecommerce-backend)

![backend API](https://cdn-images-1.medium.com/max/2000/1*RqLUUo8TgqxGavh95qTNqg.png)

### Add to cart (POST) :

In this method, we will have to send the id of the product and the quantity so that the given product can be added to the corresponding user’s cart. Hence, the body of the POST request should look like the following,

![Post Body if product id is 3 and quantity is 2](https://cdn-images-1.medium.com/max/2000/1*vTmDTZ4fgPY85gGnKJrCXQ.png)

### **Get all cart items (GET) :**

Now, to get all the items in the cart for a particular user, we need to have a GET request. In return, we will get all the product details, quantity and the total cost of items in the cart. The cartItems is the array of all products present in the cart and totalCost represents the overall cost of all the items in the cart.

![The response body in JSON format](https://cdn-images-1.medium.com/max/2720/1*Edip5kAfAiJ7Kyd48fKVUw.png)

### Update an item (PUT) :

To update a particular product in the cart, we need the cart_item_id , quantity and user_token .

### Delete the item from the cart (DELETE) :

To delete a particular product from the cart, we need the cart_item_id . We can delete that item by its id.

## The flow of this tutorial
>  *1. Add to cart*
>  *2. Display cart items*
>  *3. Update an item in the cart*
>  *4. Delete an item in the cart*

## Folder Structure

Go ahead and create a folder named Cart in the views folder of our Vue project and then create a vue.js file Cart file in the Cart folder.

The folder structure shall look like this

![Folder Structure](https://cdn-images-1.medium.com/max/2000/1*nluxKKZQXaSciV7zjFbsXg.png)

In this (Cart.vue) component we will be displaying the cart items the user has added to his cart.

Here the user will also be able to update the number of items in the cart or delete the item in the cart. Also, we will be displaying the cart price at the bottom of the page which will be updated each time user modifies the cart.

Users can also click on a particular item to view its details.

## Now let’s get to coding

We will crate a Cart.vue file which like any Vue.js file has three components

1. template tag (for writing HTML tags)

2. a script tag (for coding the logic/functionalities )

3. a style tag(for adding CSS to the page).

In the script tags, we need to export the Cart component which can be rendered in some components by importing it.

## 1. Add to cart

We will be using the **API**:/cart/add we have seen above in the **API** description.

We have a showdetails component that displays the details of the product the user wishes to view or add to the cart.

So in this component, we have a button AddtoCart that calls the post method(addToCart) of our backend API which will have a post body of the product id and the quantity of that product.

![adding a product to the cart](https://cdn-images-1.medium.com/max/2400/1*jXcyeqVkOVnSTjYbuxbWug.gif)

## **2. Displaying the cart items**

We will be using the API: [/cart/](http://localhost:8080/api/swagger-ui.html#/operations/cart-controller/getCartItemsUsingGET)getCartItems we have seen above in the **API** description.

For this, we will need data variables that we will be binding with HTML attributes

* **carts**: for storing the response data which will be fetched from the API call,

* **token**: user token to check if the user is logged in or not,

* **len**: to store the length of the items in the cart

* **totalcost**: to store the total cost of the items in the cart,

* **cartItem**: an array of objects where each object contains the following data fields :

 1. **imgUrl**: the image of the product

 2. **pName**: product name,

 3. **pDescription**: product description,

 4. **pPrice**: product price,

 5. **pQuantity**: product quantity,

 6. **id**: item id,

 7. **userId**: id of the user
{% gist https://gist.github.com/SudhanshuGulhane/6af497ac2fc52d8c55ba8d06315f9e34.js %}
From the App. vue file we pass down props to router-view components in this case Cart component receives the props therefore we store the baseURL received from the props.

Now, whenever the user is navigated to /cart i.e. Cart component is mounted/rendered we set the token value from the local storage.

![displaying the cart items](https://cdn-images-1.medium.com/max/2000/1*NaV9qj788fCEPzjWQmWoTQ.png)

***listCartItems() function***: will be used to get and display the items in the cart.

Since we want to fetch the items get method of **Axios** will be used and it will be passed the token of the user as a param. So our **backend API**, finds the user with the token provided and then according to the userID returns an array of items in his/her cart with a status code of success. But if the token provided is invalid i.e. the user is not logged in then it returns a response stating that the token is invalid.

If the response status of the **API** call we made is success then we store the data of the response in the **carts** data variable we created earlier. The response contains an array called cartItems which contains cartId, productId, userId, and a product array that contains the details of the product. Then the length of the “carts” array will give us the number of items in the cart which we will be stored in the variable “len”.

Now we iterate through the cart items using the for loop and store the details of each product in the “cartItem” array.
{% gist https://gist.github.com/SudhanshuGulhane/41f26e57d12a7bdcd5a7673c9d0fd0d4.js %}
## **Displaying the details of a product**

Whenever the user clicks an item in the cart, the user will be navigated to showDetails component where details of that item will be displayed.

***showDetails() function***: will receive a parameter i.e. the id of the product which will be passed as params in the push method of the router instance ($router) and then the user will be navigated to showDetails component which will show the details of the product according to id received. So when we click on the image or the name of the item it will show details of that item like below:

![displaying details of a particular item](https://cdn-images-1.medium.com/max/3638/1*CD2NZVlf_ns_f7hwx98AFQ.png)

Don’t worry that we have not added the HTML part and you may be wondering how is it being displayed. The HTML part I have attached at the end is to give a visualization of what we are building, So stay tuned!

## 3. Updating a cart item

![updating an item (here Towels product)](https://cdn-images-1.medium.com/max/2000/1*W0Rm1CBylgIRPtn0c9KqbA.gif)

We will be using the **API:/cart/update/{cartItemId} **we have seen above in the **API** description.

***updateItem()**: *This function will receive an index of the product in the cartItem and a new quantity

First of all, we will find the itemId in our cartItems array by looping through it and then break the loop and store the index of the item found in the variable “i”.

Then update the quantity of the product with the new quantity received from the parameters. Also, we store the userId and productId in the variables since we need to pass the response body to our backend API call. Here in this backend API too first user authentication will be done and then the item with the itemId provided will be found and thus its quantity will be updated.

Since we are updating an entity we use the put method of Axios and pass itemId and token as params and itemId, userId, productId, quantity as the response body.
{% gist https://gist.github.com/SudhanshuGulhane/b2d3a0b8fad2fc77756ca62eeed0fbef.js %}
## 4.Deleting an item from the cart

![deleting an item from the cart](https://cdn-images-1.medium.com/max/2256/1*yKXt4ynkfHkl5Gq08wew8g.gif)

We will be using the **API:/cart/delete/{cartItemId} **we have seen above in the **API** description.

**deleteItem():** This function will receive an itemId

We call the delete method of Axios which will call the backend **API **for the respective URL mapping and it will be provided with the itemId and token as params. So this backend API will first find the user with the token provided and if the user is found then the cart item with the provided itemId will be deleted from the database. After deletion, the API sends the response status as 200 the product is deleted from the cart and we refresh the page.

**Now one more point to be noted that when this component will be rendered/mounted the cart items should be displayed. Hence we call the listCartItems() method in the “mounted” method.**

    mounted() {
       this.token = localStorage.getItem("token");
       this.listCartItems();
    }

## The HTML part of our feature:

Now let’s start working on the HTML part. So in the template tags, we need to add our HTML attributes. Now we display the items if and only if the user has added them into the cart. So in general whenever conditional rendering is done we use the v-if directive of Vuejs. The block will only be rendered if the directive’s expression returns a truth value.

As we store the response data we get from our API in the “carts” variable it is used to determine whether or not to display the items i.e. if the “carts” value is not null then the div block with the v-if directive will be displayed.

Now since we may have more than one item in the cart we need to loop through the “cartItem” array and then display them. For this, we use the v-for directive which needs to be passed a key (required) to uniquely identify an item. Remember the length of cart items we stored in the “len” variable, it is used herein looping.

Now for each product we display its image with the help of the v-bind directive and on clicking that we call the showDetails() method.

Now using the two-way data binding concept of vuejs we display the name, description, price, quantity, the total price of that item.

Also, we need to add buttons for the delete and update method.

![Update button and delete button and displaying the total cost of the cart](https://cdn-images-1.medium.com/max/2004/1*oFJIbfQYTwQVAnZ8jS8M3g.png)

When the delete button will be clicked deleteItem will be called and the implementation of which we have seen earlier.

Since quantity can be updated we create a form that accepts the quantity and then submit it using the update button. We bind the input attribute with the “pQuantity” variable we created using the directive v-model.

This will call the function updateItem() which will be passed the index (recall that while implementing this method we accepted a parameter to find that product in the cart) and quantity of the product which needs to be updated.

Lastly, we display the total cost of the cart stored in the “totalcost” variable.
{% gist https://gist.github.com/SudhanshuGulhane/f1f0467143fc3b63afb6a3555b312b9b.js %}
## Congratulations!

You have now successfully displayed and updated the products added to the cart.

You can find the complete code in this [GitHub Repo](https://github.com/webtutsplus/ecommerce-vuejs/blob/master/src/views/Cart/Cart.vue)