Hello guys,
Hope you’re doing well.
So before we move towards creating the registration, login, and logout
functionality with Vue JS using Axios & Vuex, I would like you to
take a small note as a prerequisite.
Prerequisite
- Developers must have knowledge of javascript.
- Developers must have knowledge of Vue JS basics. (Including props, components, methods, etc)
- Developers should have knowledge of calling APIs. (at least with POSTMAN)
Rest assured my friends 🙂
Don’t worry if you’re not too familiar with Vue. If you’re just starting your career with this amazing JS framework. I would like you to pay attention to each step, especially if you’re a beginner.
Let’s start playing with Vue.
Installation of Vue CLI
Here we’re going to make a demo for the registration, login, and logout functionality with Vue 2. But don’t worry If you want to use Vue 3, because the same things will apply for Vue 3 as well with slight changes.
So here I am hoping that you guys have installed Vue CLI in your system. If not, then you can follow the below steps to install the same.
You can paste the below-given line to your terminal (If mac / Linux) or command prompt (If windows)
npm install -g @vue/cli
Thus, you would be able to install the Vue CLI to your system, here -g means global. So you can run the “vue” command from any path of your system.
To check the Vue CLI version, simply type the following command,
vue –version
Create a new project/application
Let’s move towards the installation of a new project. To create a new project using Vue CLI, you can simply type the following command.
vue create {project_name}
So in our case, the command would be,
vue create vue-auth-app
Now you may be asked to choose an installation.
Vue 2 (default)
Vue 3 (default)
Manual
In this example, we’re going to choose Vue 2 (default).
Run the project/application
Once your installation process is finished, you’ll have to switch to your project in the terminal/command prompt.
Now to start, run the below-given command,
npm run serve
After the process, you’ll be given a URL something like the added screenshot,
Now simply open the local URL in your browser and here you go. You’ve completely installed and run your first vue project.
Install vue-router
As we know we’re going to create a register, login, and logout example over here. So it is mandatory to have routes for the switching purpose, from one page to another.
Now we have already installed Vue CLI, so let’s do it with Vue CLI. Hit the following command to install vue-router and related stuff into the project.
vue add router
Let’s start playing with code:-
Edit default navigations
Now the vue-router has been added to your project you would be able to see 2 navigation options.
=> Home
=> About
Now let’s create one component called “Nav.vue” under the “components” folder,
<template> <div id="nav"> <div id="navbar" class="navbar navbar-expand navbar-fixed-top"> <div class="container"> <div class="navbar-brand"> Vue Application </div> <ul class="nav" v-if="!user"> <li class="nav-item"> <a href="#" class="nav-link">Login</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Register</a> </li> </ul> </div> </div> </div> </template> <script> export default { name: "Nav" } </script>
Now, we’ve to import this in our App.vue file.
<template> <div id="app"> <Nav /> <router-view /> </div> </template> <script> import Nav from "./components/Nav.vue" export default { name: "App" } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } </style>
Let’s make a login form
To create a login form we need to create one file inside the “view” folder called Login.vue
<template> <div class="container"> <form class="form"> <h3 class="text-center text-info">Sign In</h3> <div class="form-group"> <input type="email" placeholder="Enter email" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="Enter password" class="form-control"> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-info btn-md font-weight-bold" value="Sign In"> </div> </form> </div> </template> <script> export default { name: "Login" } </script>
Let’s make a registration form
To create a registration form we need to create one file inside the “view” folder called Register.vue
<template> <div class="container"> <form class="form"> <h3 class="text-center text-info">Sign Up</h3> <div class="form-group"> <input type="text" placeholder="Enter name" class="form-control"> </div> <div class="form-group"> <input type="email" placeholder="Enter email" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="Enter password" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="Enter confirm password" class="form-control"> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-info btn-md font-weight-bold" value="Sign Up"> </div> </form> </div> </template> <script> export default { name: "Register" } </script>
Add router
In your router/index.js file, you’ll have to add a new router for the login and registration. So that whenever we click on the login menu or register menu the appropriate view can open.
Let’s copy the Home router and make it similar for the login and register. Do not forget to import the view file for the same.
Link routers
Now we have to link those routers with our navigation bar because currently, we’ve not attached anything to “a” tag, also if you’ve attached the links to “href” and will click on login or register. You’ll notice that the page gets refreshed all the time. So we would handle this by replacing an “a” tag with “router-link”. It would look something like this in your Nav.vue file,
<router-link :to="{name: 'Login'}" class="nav-link">Login</router-link> <router-link :to="{name: 'Register'}" class="nav-link">Register</router-link>
Install Axios
To install an Axios, please use the following command,
npm install axios
Let’s call an APIs
Now let’s register the user by calling an API using Axios.
Open the Register.Vue file, Make the changes according to the following code,
<script> import axios from "axios" export default { name: "Register", data() { return { name: '', email: '', password: '', password_confirmation: '' } }, methods: { async handleRegister() { if (this.name == '' || this.email == '' || this.password == '' || this.password_confirmation == '') { alert("Please enter all the needed fields.") return } if (this.password_confirmation !== this.password) { alert("Confirm password doesn't match with actual password.") return } const newUser = { name: this.name, email: this.email, password: this.password, password_confirmation: this.password_confirmation } await axios.post("http://127.0.0.1:8000/api/register", newUser, { headers: { // remove all the headers } }).then((res) => { if (res.status === 201) { this.name = '' this.email = '' this.password = '' this.password_confirmation = '' this.$router.push('/login') } }).catch((err) => { console.log(err) }) } } } </script>
The same way we’ll call an API for the login. So open the Login.vue file and make the changes as per the following code,
<script> import axios from "axios" export default { name: "Login", data() { return { email: '', password: '' } }, methods: { async handleLogin() { if (this.email == '' || this.password == '') { alert("Please enter the credentials.") return } const parameters = { email: this.email, password: this.password } await axios.post("http://127.0.0.1:8000/api/login", parameters, { headers: { // remove all the headers } }).then((res) => { if (res.status === 200) { const result = res.data localStorage.setItem('token', result.data.token) this.$router.push('/') } }).catch((err) => { console.log(err) }) } } } </script>
Now let’s call the logout API,
NOTE : You’ll have to create a button or one menu beside the login and registration menu. You can render it conditionally based on whether the user is logged in or not. I’ve created as shown below,
<ul class="nav" v-else> <li class="nav-item"> <span class="nav-link font-weight-bold logout" @click="handleLogout"> Logout </span> </li> </ul>
<script> import axios from "axios" export default { name: "Nav", methods: { async handleLogout() { if (confirm("Are you sure you want to logout ?")) { await axios.post("http://127.0.0.1:8000/api/logout", {id: this.user.id}, { headers: { "Authorization":"Bearer "+localStorage.getItem('token') } }).then((res) => { if (res.status === 200) { localStorage.removeItem('token') this.$store.dispatch('user', null) this.$router.push('/login') } }).catch((err) => { console.log(err) }) } } } } </script> <style scoped> .logout { cursor: pointer; } </style>
Redirection after login
To redirect after login we’ll just write the below-given line on the successful response of login API.
this.$router.push('/')
Let’s open the Home.vue file and call an API to fetch the logged-in user. Once the API call succeeded we will set the logged-in user detail to Home.vue as well as Nav.vue file. Because based on the user’s login status we’ll switch the menus (login & register or logout)
So here in both files, we’ll have to write the same code to display user-related data and have to render the menu conditionally. So we will call an API for that in the App.vue file instead of Home.vue & Nav.vue (We’ll cover that code after the vuex installation)
So here we bring the vuex because it may happen after calling the login API, when you redirect to the “/” URL, the created() calls an API to fetch the logged-in user data. But it may not reflect and for that, you have to refresh the page to see the login user details.
So let’s install vuex.
Install vuex
You can use the following command to install vuex to the project,
npm install vuex
Here in this example we’re not going in deep for vuex.
Setup vuex file
Let’s create a file in src directory called “vuex.js”
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const state = { user: null, }; const store = new Vuex.Store({ state, getters: { user: (state) => { return state.user; }, }, actions: { user(context, user) { context.commit("user", user); }, }, mutations: { user(state, user) { state.user = user; }, }, }); export default store;
Don’t forget to import the store in the “main.js” file. So your main.js file would look like,
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./vuex"; Vue.config.productionTip = false; new Vue({ router, store, render: (h) => h(App), }).$mount("#app");
Now we’ve to use the vuex so that we can have the instant effect of the data once its state changes.
So here we go for the App.vue file code. Which will call an API to fetch the logged-in user and set the user state using vuex.
<template> <div id="app"> <Nav /> <router-view /> </div> </template> <script> import axios from "axios" import Nav from "./components/Nav.vue" export default { name: "App", components: { Nav }, async created() { try { const res = await axios.get("http://127.0.0.1:8000/api/user", { headers: { "Authorization":"Bearer "+localStorage.getItem('token') } }) if (res.status === 200) { this.$store.dispatch('user', res.data) } } catch (err) { console.log(err) } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>
After that, keep the following line in your “Login.vue” file before you redirect to “/” URL.
this.$store.dispatch('user', result.data.user)
Now you’ll have to add a computed property and import the mapGetters to fetch the current user value for Home.vue and Nav.vue file.
import { mapGetters } from "vuex" computed: { ...mapGetters(['user']) }
Also when you call the logout API, please add the following line before you redirect the user to the login page.
this.$store.dispatch('user', null)
So that the user value is set to the default value “null”.
Hope this example makes sense. Please comment if you’re stuck somewhere in the middle of any error while implementing the same.
Here you can grab the actual code of this vue application,
Here is the link for the GIT repository
vue-auth-app
Quick recap
- We’ve created a vue project.
- We’ve installed vue-router in the project.
- We’ve made a “Nav.vue” file and added our html for the login and registration menu.
- We’ve made register and login view files.
- We’ve called an API to register new users and log in.
- We’ve installed the vuex in the project.
- We’ve made a “vuex.js” file in the /src directory.
- We’ve called an API to fetch the current user in App.vue
- We’ve added user detail to render conditionally.
- We’ve called the logout API.
- We’ve added the dispatch store code of vuex.