Creating an eCommerce Frontend with Vue.js
Tags: webdev, javascript, programming, vue
Published: 2021-01-19 22:25:04


## Let’s Develop an E-Commerce Application From Scratch Using Spring Boot and Vue.js

Project set up and building admin panel for managing Category in Vue.js

![](https://cdn-images-1.medium.com/max/3788/1*T44BfYTTAI3Dj7B47YtzHw.png)

## Motivation

In my opinion, the best way to learn programming is to create a real-life project which has practical use. This way, the entire learning experience becomes quite exciting. Also, you can showcase your app in your portfolio, which can help you a lot if you want to land a freelancing gig or in an interview.
> # This tutorial is perfect for people who are starting their journey in Vue.js as we build it from scratch, integrate remote API call, router, break down UI into compoenents, form handling as well as cover some important concepts like v-model, v-on.

In this series of blogs, you will amplify your development skills by learning how to build an e-commerce platform from scratch. I am good at backend development, and I wanted to learn Vue.js, so I learned it by creating this project. I wanted to share what I built, so I choose medium.com to share my journey.


## What we will cover in the tutorial

This tutorial will focus on the front-end.

 1. Set up a Vue.js project

 2. Configure router, API call, sweet alert

 3. Create a dashboard to list all the categories present in the backend

 4. Adding and Editing Categories.

## Video tutorial

{% youtube PDDXAztk6xg %}

As part of building an E-Commerce application, previously we have configured the back end of this App and developed some APIs using Spring boot. If you are interested, you can check out this [tutorial](https://medium.com/javarevisited/lets-develop-an-e-commerce-application-from-scratch-using-java-and-spring-a921f448a93b). But if you are only interested in the front-end, you can start directly from here.

Every e-commerce store like Amazon will have millions of products, and they often belong to a category. For example, a shoe category consists of many shoes which are products. There can be a category, a sub-category, but for simplicity, we will just take categories and products.

![](https://cdn-images-1.medium.com/max/3840/1*SiNToBQgtsPUrXfpAdk_0w.png)

Now, let us see how to configure the front-end and create the user interface for category using one of the most popular JavaScript frameworks — Vue.js. Let’s get started!

## Final Demo

At the end of the tutorial, we will

**list all categories**

![](https://cdn-images-1.medium.com/max/2596/1*MB6aoXw_YhFz6z-OkVlhMA.png)

**Add a new category**

![](https://cdn-images-1.medium.com/max/3240/1*gH52b663GaVfVP03n-73Gg.png)

**Edit a category**

![](https://cdn-images-1.medium.com/max/2000/1*6UkmaAjlkpmz_E2CxNXFRg.png)

## Start the project

Let’s get started.

![Photo by [Braden Collum](https://unsplash.com/@bradencollum?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/6962/0*a9HbxKloNHUNXK02)

Open the command line and execute the following command to initiate a new Vue project, assuming you have vue.js installed or go to this [link](https://v3.vuejs.org/guide/installation.htm).

    > vue create ecommerce-ui

The command should work properly if you already have Vue CLI installed. Next, it will ask for some project configurations. Give the following data for configuring our front end Vue app:

![](https://cdn-images-1.medium.com/max/2594/1*gQaMQVZVo-4uLF-v1Fk5Qg.png)

After confirming all the details, we will have a project folder created for us by Vue CLI.

Go to the project folder and give the following command to run the application

    > npm run serve

After the server got hosted and the application is started, you can go to http://localhost:8080/. The response should be something similar to the output, as below-

![](https://cdn-images-1.medium.com/max/2386/1*Ab9tW8hDJtmChUPoU5jmxQ.png)

Yay! We have created our Vue app. Already off to a good start.

![Photo by [Peter Conlan](https://unsplash.com/@peterconlan?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/10944/0*MZ9OVQ5HC1wZD0fp)

The project will have some files with .vue extension, which are called Vue components.

## Vue Components

Almost all frontend frameworks allow us to create components that we can reuse at multiple places on the same or different websites. Some examples include a search bar, login form, product display component, etc. In Vue, files with “.vue” extension are known as single file components. These single file components are composed of HTML, JavaScript, and CSS.

    <template>
      <!-- HTML Template -->
    </template>

    <script>
      export default {}
    </script>

    <style>
    </style>

* The template part contains the HTML of the component.

* The script tag contains the code defining the custom behavior of the component.

* The style tag houses the CSS of the component.

* src/components and src/views contain all our components.

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

## Folder Structure

Let’s go through the folder structure of our newly created Vue project

* **public **— contains the main HTML file of our project

* **src/assets **— stores the media files like images, logos, etc.

* **src/components **— stores all the reusable components of our project. These components are not unique to some specific route.

Apart from this, we have some important files too

* **App.vue **— it is the root component of our project

* **main.js **— it is the starting point of our project. Here we import our root component **App.vue**, our router file **index.js** and **createApp** method. After this, we mount our root component to the DOM using the following statement:

    new Vue({
      render: h => h(App),
    }).$mount('#app')

The folder structure is not enforced by Vue, we can customize this as per our requirements.

And now we have our basic version of the front-end of our App where we will work more to add more functionalities. The basic project structure can be found in the following GitHub repository.
[**GitHub — webtutsplus/ecommerce-ui at setup**](https://github.com/webtutsplus/ecommerce-ui/tree/setup)

## Building the UI for Category

Once the basic structure is ready, we will start building the dashboard for categories.

We will first add a router to our project. Run the following command in your command line to install the Vue router in your system

    vue add router

When asked to choose history mode, choose yes. Now if you run the app, you will see two links in the above.

It will create a router directory with index.js file inside it. Also, it will create a views directory, with two files inside it, which are

 1. About.vue

 2. Home.vue

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

If you run the front end application using the command ***npm run serve***, you will see two links on thehomepage.

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

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

We still have Helloworld component, let’s delete that. Also delete lines 4 and 10 and 15 from Home.vue, containing the Vue logo image and references to HelloWorld.
{% gist https://gist.github.com/nilmadhab/79e66625b4ed98782fde4b7567006afd.js %}
If you run the app, you will see the following screen.

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

### Styling the App

Open the file index.html and replace the content with the following code.
{% gist https://gist.github.com/giridhar30/7130fe2f2a60829b977577a9d3b89e48.js %}
We just added some basic fonts, bootstrap.css and jQuery.

## Adding a Category

Time to create a form for adding category.

 1. We will create a directory Category inside the views directory.

 2. Create a file *AddCategory.vue *inside it

 3. Add the content given below, which contains the form that takes input data for creating a category
{% gist https://gist.github.com/nilmadhab/9b132d6efb9d7b06b98433dfa3ca6817.js %}
### v-model binding concept

As you can see, in the form, we have used v-model=”categoryName”. This is an important concept in Vue.js called [Form Input Bindings](https://vuejs.org/v2/guide/forms.html).
> # You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements. It automatically picks the correct way to update the element based on the input type. Although a bit magical, v-model is essentially syntax sugar for updating data on user input events, plus special care for some edge cases.Updating Router Paths

For our single-page application to run properly, we need to create router paths for our newly created components. Go to src/router/index.js file and update it as below by adding as well as importing AddCategory component.

    {
        path: "/admin/category/add",
        name: "AddCategory",
        component: AddCategory,
      }
{% gist https://gist.github.com/nilmadhab/856f5d9074fcd7b7d49db27e45901bc4.js %}> # Notice although we have vue components both in views and components directory, the main difference is we use vue components in views directory to use in router, i.e each vue components in views directory mapped to a route.

Now if we go to the page [http://localhost:8080/admin/category/add](http://localhost:8080/admin/category/add)

![](https://cdn-images-1.medium.com/max/2490/1*_vFIdmIAYW4fdX5EJCe8QA.png)

### Axios and sweetalert integration

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node

 1. Run the command npm install --save axios

 2. We add the following line in main.js window.axios = require('axios')

 3. We will also install the package npm install --save sweetalert

### API call

 1. First, we will trigger addCategory function, by clicking the submit button. We can do it easily by adding the code @click="addCategory" in submit button, so it looks like this
{% gist https://gist.github.com/nilmadhab/3d6032be555a8203119633fa4f81c128.js %}
We will define a function in the methods section inside the script tag.

### Base url

We have hosted our backend on Heroku, which you can access by the endpoint, [https://limitless-lake-55070.herokuapp.com/swagger-ui.html#/category-controller](https://limitless-lake-55070.herokuapp.com/swagger-ui.html#/category-controller/getCategoriesUsingGET)

We will define [https://limitless-lake-55070.herokuapp.com/](https://limitless-lake-55070.herokuapp.com/) as our base url and to create a new category, we need to hit,

For adding a new category, we need to hit the baseURL + “category/create” with this JSON with a post request, of request body.
{% gist https://gist.github.com/nilmadhab/28afe6a0d9c688e9d67294e6f418d1f7.js %}
Which we will implement in the script section.
{% gist https://gist.github.com/nilmadhab/054405a1107f174a561ec537b74ae1e6.js %}
![](https://cdn-images-1.medium.com/max/2256/1*qOyjueQLHgE1HozHbdKyhw.png)

The complete code until this stage of this application can be found in the GitHub repository given below.
[**GitHub — webtutsplus/ecommerce-ui at category-add**](https://github.com/webtutsplus/ecommerce-ui/tree/category-add)

![Photo by [IA SB](https://unsplash.com/@iasb?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/12000/0*BClSZbSwiZ6H_mwj)

Nice job guys, if you succeeded in making it so far. Next, we will start with displaying the categories. If not, you can run the above Github repo in your local machine, it should work.

## Displaying the Categories

Now, we can create a new category, time to display all the categories in a nice manner.

Our final result of displaying the categories will be as shown below-

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

## Component Breakdown

To display all the categories, we need to create a view for that. Create a file named Category.vue under src/views/Category folder. This view is used to display the categories that are fetched from the database. This view also holds the references that will redirect us to AddCategory view.

In modern frontend framework like Vue.js/react, we break down our UI into small components for reusability.

Here we will also break down this by each category. This will be a component-

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

## CategoryBox.vue component

We will create a directory Category in src/components and create CategoryBox.vue file in it.

It will have a prop category which will be passed from a parent view, and it will just display the category with an option to go to the edit page, which we will build in the next chapter.
{% gist https://gist.github.com/giridhar30/ea77b6094f32a1bde33c93ba8bddd910.js %}
## Category.vue component

Now it’s time to create the component for listing all the categories!

This component fetches the categories from the back-end using axios and passes each category as a prop to CategoryBox component, which displays each category. Finally, the component will be a collection of categories displayed in CategoryBox components.

Go to src/views/Category/Category.vue file that we have already created and update it with the following code!
{% gist https://gist.github.com/giridhar30/c209a205ce342a97b44517ec7e1a71b9.js %}
## Updating the Routes

And as the final step, let us create the router path for this component to display all the categories. The following route will be appended to the routes-

    {
        path: "/admin/category",
        name: "AdminCategory",
        component: Category,
    }

The complete index.js file is as below-

    import Vue from "vue";
    import VueRouter from "vue-router";
    import AddCategory from "../views/Category/AddCategory";
    import Category from "../views/Category/Category";

    Vue.use(VueRouter);

    const routes = [
      {
        path: "/",
        name: "Home",
        component: Home,
      },
      {
        path: "/about",
        name: "About",
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/About.vue"),
      },
      {
        path: "/admin/category/add",
        name: "AddCategory",
        component: AddCategory,
      },
      {
        path: "/admin/category",
        name: "AdminCategory",
        component: Category,
      },
    ];

    const router = new VueRouter({
      mode: "history",
      base: process.env.BASE_URL,
      routes,
    });

![](https://cdn-images-1.medium.com/max/2372/1*G0FATh9mPwtfPWCtrVM1LQ.png)

The complete code until this stage of the application can be found in the GitHub repository given below-
[**GitHub — webtutsplus/ecommerce-ui at category-display**](https://github.com/webtutsplus/ecommerce-ui/tree/category-display)

![Photo by [Nick Fewings](https://unsplash.com/@jannerboy62?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/6064/0*MaB9sxu8wsq2LBUz)

Keep going on guys. Next we will move to editing category.

## Editing a Category

Open src/views/Category folder and create a file for EditCategory view with the boilerplate code as below.

Pretty simple, we are just defining the three sections, template, script and style.
{% gist https://gist.github.com/nilmadhab/0b79629e53bdc3b66807bd64a858323f.js %}
## Add the form

Now, we will add the form to edit the category. It will be a form similar to AddCategory view. We also define 5 variables id, categoryName, description, imageUrl, categoryIndex and initialize those to null. We will also define the baseUrl
{% gist https://gist.github.com/nilmadhab/ca733acf661a1d0a6c006fde79591304.js %}
## Send the category data to view

Now the question is how do we get the data from the Category home page to this view. The answer is simple. First, we create a router for the view. We set props: true at line 5. We will pass the Category data which we need to edit as prop.
{% gist https://gist.github.com/nilmadhab/74ed9fa21c2efe4a40a5113d5d28b5da.js %}
## Add option to edit

Now, we will add an option to edit a category in the CategoryBox. Line number 10–12.
{% gist https://gist.github.com/nilmadhab/c245a60119fd419bc3a283aa4af92de4.js %}
![](https://cdn-images-1.medium.com/max/3840/1*syXZUPc9Op9zjoPk3Ez_2Q.png)

## Update the script

Now, we will create one prop category and in the mounted section we populate all the data.
{% gist https://gist.github.com/nilmadhab/6908197442baff2958f2e90f3f63597d.js %}
That’s it, now if we click the edit button in categoryBox, we will see the data.

![](https://cdn-images-1.medium.com/max/3074/1*sEs9WyAfWpZXXzizA6Hi_Q.png)

## API call to save the data

Now, we have only one thing left, how to update the data in the remote server?

We will define a function editCategory in the method section. We will call this function in the submit button.

<button type="button" class="btn btn-primary" @click="editCategory">Submit</button>
{% gist https://gist.github.com/nilmadhab/c0f25f353bcb0a85690b9cbe3169c36d.js %}
![](https://cdn-images-1.medium.com/max/2294/1*oSo4wA1XSSJpJbwGj03GfQ.png)

The complete code for EditCategory.vue
{% gist https://gist.github.com/nilmadhab/b7f1f194b2908b47b5f7d87f8df3d140.js %}
The complete project for this tutorial can be found in the GitHub repository given below-
[**GitHub — webtutsplus/ecommerce-ui at category-edit**](https://github.com/webtutsplus/ecommerce-ui/tree/category-edit)

Hurray! We have completed the part of building the front end to create categories using Vue.js! But wait! There are a lot more to learn in this tutorial series! Stay tuned until then!

Let me know in comment, if you like the tutorial, or you like any improvement to understand it better,

***Happy learning!***

*More content at [**plainenglish.io](http://plainenglish.io/)***