Creating a simple Vue.js website for our backend

Creating a simple Vue.js website for our backend

How to build UI in Vue.js for JAVA Springboot backend

Introduction

Thus far we have been able to create a basic REST API using Spring Boot and A Simple User Authentication API made with Spring Boot These days its easier than ever to make a proper application that can do what you need it to do. There are thousands of…medium.com

we have been able to upload it to Digital Ocean so that it can be accessed How to Publish Your Spring Boot App to the Cloud Introductionmedium.com

from the web. Although, even as someone who prefers the backend over the front end, I will admit that the API alone is pretty boring, so today we will use Vue.js 3 to add a graphical user interface to the API so that it will be less boring.

Also Checkout our latest series Let’s develop an Ecommerce Application from Scratch using Java and Spring We are going to build an e-commerce application from scratch using Java, Spring backend, build web UI in Vue.js, and…medium.com

Demo

You can see the final demo here and try it out. web-tutorial Edit description139.59.208.56

Requirements

To get this started we will need to install NodeJS as we will use it to work with Vue.js. To get NodeJS you can head on over to their website to get NodeJS, personally, I will suggest that you go with the LTS version since it should be a lot more stable. For the Linux users, I would suggest using the Node Version Manager, since I have found some issues with how Linux handles the files and permissions, although it’s only a suggestion.

To test whether or not you have successfully installed NodeJS, you can open your terminal and run this command:

node -v && npm -v

It will give you the version of NodeJ that you have installed and the version of NPM (Node Package Manager) that you have installed.

Now that you have Node and NPM installed we can move on to installing Vue’s CLI (Command Line Interface). Open your terminal or cmd, and inter this command to install the CLI:

npm install -g @vue/cli

This command tells npm to install Vue.js’ CLI globally (-g), that way you can use the CLI commands without needing to install the CLI per directory. If you get an error that complains about not having permission, then it’s because NPM doesn’t have the required permission to alter a file. I kept having permission errors and that’s why I ended up using Node Version Manager.

You can test your newly installed Vue.js’ CLI by typing this command into your terminal:

vue -V

You will also need an editor or IDE. Personally, I am going to use VS Code, but feel free to use what you are most comfortable with.

Lastly, if it wasn’t obvious yet, you will need to have a web browser installed on your computer. Something like Google’s Chrome, Mozilla’s Firefox, Microsoft’s Edge, Chromium, or even Apple’s Safari.

NOTE: I am going to be interfacing with the cloud server I created in the last tutorial, but if for some reason the server is no longer available by the time you are reading this, you can download the source code for the server and run it on either your own VPS or on your localhost.

Now let’s get hacking, shall we?

Setting up the project

Head on over to your development folder and open your terminal in that file. Type this command:

vue create web-tutorial

This command is telling the Vue.js’ CLI to create a project called web-tutorial, although feel free to name the project whatever you want. Next, you will be asked to choose what preset you want to use to create your project, using the arrow keys, move down to “Manually select features” and then click “Enter”.

Next, you will be asked to check which features you want access to in your project, for this you will want to select: Babel, Router, and Linter / Formatter. If you move down to an option, you can select it by pressing “Spacebar”. Once you have those three things selected you can press enter to continue.

We will be using Vue.js 3 so move down to “3.x (Preview)” and then press “Enter”.

Next, it will ask if you want to use history mode for the router, you can just say no by typing “n” and then pressing enter “Enter”.

For the linter we just want ESLint with error prevention, so you can just press “Enter”.

For the additional lint features you can just press “Enter”.

We would prefer it if our configs for Babel and ESLint are in their own dedicated files so we can just press “Enter”.

When it asks if you want to save this as a preset you can just say no (“n” and then “Enter”), although you can also save it if you really want to.

Phew! Finally done with setting up your project options, Vue.js CLI will generate your project from the options you selected. This might take a while so feel free to stretch your legs for a bit.

You will notice that Vue.js has recommended some starting commands for us to run, let’s see what they do. The first command changes your terminal’s active directory to the one we just created (cd web-tutorial), the second command creates a development server which will host our code on a local server that will automatically refresh if any changes have been detected in the source code. After working with Java and Spring Boot, the hot reloading is a welcome change, it was annoying having to constantly restart our server manually. If we now open HTTP://localhost:8080 in our browser we should see this website:

This is the default prebuilt website that Vue.js generated automatically for us when we created the project. Now that we have the development server up and running we can open the project inside our text editor or IDE, in my case that would be VS Code. As usual, feel free to look around at the code but try not to change something without knowing what it does, as this can result in weird bugs and a lot of googling to try and find the answer, trust me I would now.

Let’s make a website

All the important code can be found in the “src” folder. “src/main.js” is the main entry point for our project. “src/views” is where all our web pages can be found. “src/router” is where the logic for the router is initialized. “src/components” houses the something which is referred to as a “component”, Vue.js is very modular in its design and you can use components as a way of building a website with bits and pieces of reusable code. “src/assets” houses the assets, like pictures, of our website.

Now that we know what the important parts are we can start off by deleting the parts that we won’t be using. You can delete “src/components” since our website will be pretty basic. You can delete “src/views/About.vue” and “src/views/Home.vue”, we will be creating different pages altogether.

Next, let’s open “src/App.vue”. You can sort of think of this as the main wrapper of our website. Vue code tends to be structured in three parts. The first part is the “<template></template” part, this is the GUI (Guided User Interface) layout code or the HTML code, the second part is the “<script></script>” part, this is the logic part of our code, the last part is the “<style></style>” part, this is where we store the design part of our webpage. To start off with we will just replace the template part of “src/App.vue”:

<template>
  <router-view/>
</template>

We just removed the navigation bar at the top of the screen to make it easier to work with. Next up we need to create three new files in “src/views”. The first file will be called “Login.vue” (“src/views/Login.vue”), the second file will be called “SignUp.vue” (“src/views/SignUp.vue”), the third file will be called “LogOut.vue” (“src/views/LogOut.vue”). Next, we need to create the scaffolding of each file, so let’s start off with “src/views/Login.vue”:

Let’s start off with explaining the template part:

h1: This is a header tag with a value of Login.

Next is the script part:

We need to export this view so that it can be accessed from other parts of our application. Technically speaking all .vue files are considered components, so I will be referring to them as such. We give our Login component a name of “Login”.

Finally the style part:

We give the body of our site a width of 80% so that it will have a bit of white space on both sides, it just makes our website look a bit neater. We state what font family to use, we give it some padding at the top and bottom, we set the font size, and remove the margin. CSS is a very complicated topic and I can’t even pretend to be a pro at it, so I will only be able to explain it to you at face value.

We stipulate the values for inputs, text areas, buttons, paragraphs, div’s, sections, articles and selects as having a display of block, a width of 100%, font-family of sans-serif, the font size of 1em, and a margin of 0.5em.

We also have a special class of “warning” which will be used to turn warning text’s color red.

The CSS will be the same across all the pages, that is why I covered it here.

Next up is “src/views/SignUp.vue” (this will almost be a copy of Login.vue):

The code is a lot similar to that of “src/views/Login.vue”, but with two differences. In the header tag (h1) we changed the text to “Sign Up” and we also changed the name of the component to “SignUp”.

The last page is “src/views/LogOut.vue”:

Again we just changed the header tag to say “Log Out” and we changed the name of the component to “LogOut”. With the foundations laid out before us we need to add these newly created pages (or components) to our router. So let’s edit “src/router/index.js”:

So we imported our Login, SignUp, and LogOut components, and then added a route to each one, and that’s all we changed in this file. The rest of this code was generated by the CLI. Now if you open your website you should see something like this:

If it doesn’t look like this then just check that your development server is still running (npm run serve).

Building a login page

Now, this code is a bit long so I will try to break it up as much as possible while I explain it, and then at the end, I will show it all together. To start, let us look at the template part of the login page, “src/views/Login.vue”:

So we still have the header tag saying that this is the login page.

Next up is another header tag, but this one is h3 rather than h1 so it’s a bit smaller than the h1 tag. The v-if part of the header tag is unique to Vue.js, it is similar to the normal if-statement of Javascript, it simply says that we only want to show this sub-header if the variable “error” has a value of “true”, the variable has been set in our script tag so we will get to it momentarily. The “{{errorMessage}}” part is used to show the contents of the “errorMessage” variable which we will initialise in the script tag.

After that, we have a form. A form is similar to the type of form you would get outside of cyberspace. The “@submit.prevent=”logIn””, states that when we submit this form to be evaluated we don’t want it refreshing the page, and we want it to run the function called “logIn”, this function can be found inside of the script tag.

The labels, as the name suggest is a label for that specific field which follows up next inside the form.

The first input is of type text meaning that we will handle it the same way we handle a normal text input. We give it a name, id, and v-model of type “username”. v-model binds the value of our input to the variable inside the script tag, called “username”.

The second input is of type password so it will censor whatever we type in the input box. We give it a name, id, and v-model of “password”.

Lastly, we have a router-link to our signup page, this is a Vue.js specific tag. It will be used to route our website to the SignUp page.

Next up is the script tag of “src/views/Login.vue”:

To make it easier to explain specific parts of our code, we will break it up into snippets.

import { ref } from 'vue';
import router from '../router/index';

First, off we import ref, which is a special type from Vue which allows us to create references with specific values, this has to do with data management, and we also import router so that we can change routes using Javascript.

setup() {
    const username = ref('');
    const password = ref('');
    const error = ref(false);
    const errorMessage = ref('');

So we create a special function that will be used to set up the code for this component. This function is part of the Vue.js 3 functionality.

We create a few constant references called, username, password, error, and errorMessage. Username will be used to store a reference to the username the person enters, we initialize it to an empty string. Password is a similar case to the username variable. error, as we’ve seen before will be used to determine if we need to show an error message. And if we need to show an error message we will set errorMessage equal to the message we want to show so that we can have dynamic error messages.

We create an async function called logIn. This function will be called when the user submits the forum. The reason this function has to be asynchronous is that we want to wait for the reply from the server, otherwise we end up with very weird outcomes, which you can test by removing the async part of the function and seeing what happens.

We check to make sure that the user entered a username and a password, otherwise, we throw an error message using our subheader.

If the user entered a username and password we pass it to a special function that contacts the server. We wait for the function, using the await keyword, to give us back the information from the server.

If the response is “SUCCESS” we hide the error message and reroute the user to the logout page, using “router.push(‘logout’)”, we have to specifically pass the route we want to go to, the route was set in the “src/router/index.js” file.

If the response is not “SUCCESS” we throw an error message.

This function is used specifically to talk to the server. It takes a username and a password. It is also asynchronous because we have to wait for a reply from the server.

We create a new variable called data and initialize it to a JSON value of “FAILURE”, we do this because we want our website to function even when we are unable to talk to the server.

Fetch is a special function that’s part of the web standard for Javascript. It allows us to send a POST request to our server and get information back. The first value is where we want to send the post request to, you can change this to your server’s IP address or to localhost. We specify that we want to send a POST request. In our header, we stipulate that we are going to send JSON. In the body, we put our JSON data, in this case, it’s the username and the password. The function returns a promise containing an HTTP response, so we need to extract the JSON data using “resp.json()”. Then we get that JSON data and set it equal to our “data” variable. If there are any errors we just log them to our console.

Lastly, we just return the data we received.

return {
      username,
      password,
      error,
      errorMessage,
      logIn,
    };

Lastly, we need to return all the functions and variables we created so that they can be accessed by the rest of the component. Here is the full source code to “src/views/Login.vue”:

Next up is “src/views/SignUp.vue”, although I will just give you all the source code from the start since there isn’t anything we haven’t already discusses, and I see no reason to repeat myself on a written document:

Lastly, we have “src/views/LogOut.vue”:

You should now have a fully working front-end website that can interface with the back-end we created previously. You can find the full source code here.

You should now have a fully working front-end website that can interface with the back-end we created previously. You can find the full source code here.

Thank you for reading this.

Have a lovely day!