Form Handling With API Tutorial

Abanoub GeorgeAbanoub George
5 min read

The Vue CLI is an awesome tool to kick-start your Vue projects. But by default — and rightly so — it comes with very little in the way of styling. Follow along and I’ll show you how to Create a Form With API using JSON Server on Vue

Getting set up the Vue Project

In order to show every step from start to finish, I’m going to create a new project from scratch. If you already have a project (that you set up with Vue CLI 3), you can skip this section.

If you don’t already have Vue CLI version 3, install it.

Once the app is created, move into the directory and serve the app.

> cd vue-form-api
> npm run serve

Your new Vue app is available at http://localhost:8080/

Image description

Getting set up the JSON Server for API

JSON Server Creating demo APIs For Your Project

You can check the JSON Server [https://www.npmjs.com/package/json-server] we can use JSON Server and run it by following steps

  • Install it npm i json-server
  • in you Project will create the new folder and add the db.json like we did in this project Image description
  • last step we just need to run the JSON Server json-server --watch Backend/db.json

Image description

Adding Bootstrap styles

I’m going to add a Bootstrap component to the app Still inside the vue-form-api directory, install Bootstrap and its dependencies

> npm install bootstrap jquery popper.js

Note: If you’re not going to use Bootstrap’s JavaScript, and only going to use its styles, don’t worry about installing jQuery or Popper.js.

Finally, import it into the main script by adding these lines to the top of vue-form-api/src/main.js:

> import 'bootstrap'
> import 'bootstrap/dist/css/bootstrap.min.css'

Again, if you only want the styles, and not the JavaScript functionality, just leave off the first line and only include the CSS.

Note: we will clear the Project from unused files

Add Html Form using Bootstrap Form and add a small table

            <!-- Title -->
            <h1 class=" text-info border-bottom py-2 ">Vue Form API</h1>
            <!-- Form -->
              <form class="row g-3  p-3 shadow mt-4 rounded">
                <!-- First Name -->
                <div class="col-md-6">
                  <label for="inputFirstName" class="form-label">First Name</label>
                  <input required type="text" class="form-control" id="inputFirstName">
                </div>
                <!-- Last Name -->
                <div class="col-md-6">
                  <label for="inputLastName" class="form-label">Last Name</label>
                  <input required type="text" class="form-control" id="inputLastName">
                </div>
                <!-- Email  -->
                <div class="col-md-6">
                  <label for="inputEmail" class="form-label">Email</label>
                  <input  required type="email" class="form-control" id="inputEmail">
                </div>
                <!-- Password -->
                <div class="col-md-6">
                  <label for="inputPassword" class="form-label">Password</label>
                  <input required type="password" class="form-control" id="inputPassword">
                </div>
                <!-- Address -->
                <div class="col-12">
                  <label for="inputAddress" class="form-label">Address</label>
                  <input  required type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
                </div>
                <div class="col-12 text-center">
                  <button type="submit" class="btn btn-primary ">Submit</button>
                </div>
              </form>
          </div>
          <div class="col-md-6">
            <!-- List User Information -->
            <div class="user-info ">
              <h1 class=" text-info border-bottom py-2">Users List</h1>
                  <table class="table table-striped table-dark mt-4 ">
                    <thead>
                      <tr>
                        <th scope="col">Full Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">password</th>
                        <th scope="col">address</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr >
                        <td></td>
                      </tr>
                    </tbody>
                  </table>
            </div></div>

Store the Data

we will create the object that has all data from inputs we will store it in userInfo Object

  data() {
    return {
      userInfo:{
        firstName:'',
        lastName:'',
        email:'', 
        password:'',
        address:'',
      }
    }
  },

We Will Use v-model to bind the value form inputs

Note: v-model is the two-way data binding in Vue.js bind the value from inputs

Image description

Note: we use the v-model like v-model="userInfo.firstName" userInfo.firstName write the userInfo as the main object and access the keys from this object

Add Function to get all Data

   methods : {
    addUser(){
      // we will send the Data from Here
    }
  }
  • add function addUser in methods to get all data from the userInfo Object and Send it to API
  • add the Function addUser in Form to handle the Function Note : @submit.prevent="addUser()" use the prevent To stop this behavior,

Create Services Folder and Add our Calling API Function

  • we create a new folder Services then add the file Users.services.js Image description
  • install the Axios Library Axios is a Javascript library used to make HTTP npm i axios

####Import and make Variable

  1. Import Axios to use
  2. Add base Url when we call the API each time did not need to write it we will store it in Variable

####We will Add Class and Functions

  1. Add a javascript Class to contain our Functions UsersManageServices
  2. Add the First function to Get all Users to form API getAllUsersServices
  3. Add Second function to Add New to APIaddUsersServices
import axios from 'axios'

const baseUrl = axios.create({baseURL:'http://localhost:3000'})

// Users Information Class
class UsersManageServices {

 // Create a Function for get All Users
  static getAllUsersServices() {
    return baseUrl.get('users')
  }
// Add New User
  static addUsersServices(user) {
    return baseUrl.post('/users' , user)
  }
}
export default UsersManageServices

Import our Services in our App.vue

  1. Import UsersManageServices
    // Import Users Services
    import UsersManageServices from '@/Services/Users.services'
    
  2. Add new variable in data Object to store the Data from API
    // it will be an empty Array for now
     AllUsers:[],
    
  3. You Remember our Object userInfo who store your data from Inputs
    // it will be our Object to send the Data to API
      userInfo:{
         firstName:'',
         lastName:'',
         email:'', 
         password:'',
         address:'',
       },
    
  4. in our methods we will add a Function to add a new User

    we already have UsersManageServices Class then we need to access the addUsersServices function and send our userInfo Object as Parameter

     addUser(){
       UsersManageServices.addUsersServices(this.userInfo).then(res => {
         console.log('Added Success')
       }).catch((error) => {
         console.error(error)
       })
     }
    

    Image description

Image description

  1. Then we need to list your users to table so we will add a Function to list the users

    we already have UsersManageServices Class then we need to access the getAllUsersServices function to get the users and store it in AllUsers our empty Array

    // Get All User 
     getAllUser(){
       UsersManageServices.getAllUsersServices().then(res => {
         this.AllUsers = res.data
       }).catch((error) => {
         console.error(error)
       })
     },
    
  2. we have the data stored in AllUsers will add it to our table

    we will check first if our Array has a data or not v-if=" AllUsers" then use the v-for to loop in our Array of Object to show the data , Image description our Table will be like That Image description

#Finally the Form and User Information will be like

Image description

You can find the Code in [Github] 😍(https://github.com/abanoub2017/vue-form-api)

You can Follow Me in [Linkedin] 😍(https://www.linkedin.com/in/abanoub-george-9235b1160/)

And that’s it! I hope you enjoyed 😍

1
Subscribe to my newsletter

Read articles from Abanoub George directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abanoub George
Abanoub George

Hi 👋, I'm Abanoub George A Senior Frontend Developer From Egypt I'm a 4+ experienced Frontend Engineer with solid experience in UI/UX Designing, I enjoy using my obsessive attention to detail, my unequivocal love for making things, and always being excited to make a significant impact and go through new challenges. 🌱 I’m currently learning Vue3, Node,Docker, Nginx, Tailwind CSS, Nuxt