Form Handling With API Tutorial
Tags: vue, javascript, bootstrap, api
Published: 2022-01-14 21:59:49

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](https://cli.vuejs.org/guide/installation.html).

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

```javascript
> cd vue-form-api
> npm run serve
```
Your new Vue app is available at [http://localhost:8080/](http://localhost:8080/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvbxsu8a9q0e11bazc23.PNG)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86qpz30e8jgebq8dyc83.PNG)
- last step we just need to run the JSON Server 
`json-server --watch Backend/db.json`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrcv5glgrrj32qnxznyb.PNG)

### 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](https://getbootstrap.com/docs/4.0/getting-started/javascript/#dependencies)

```javascript
> 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:`
```javascript
> 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
 ```javascript
  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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mq24o9e1ik5fuv4l48n.PNG)
> 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
 ```javascript
   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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p28u2d783gbfcm4ac26d.PNG)
- 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
3. Add a javascript Class to contain our Functions `UsersManageServices `
4. Add the First function to Get all Users to form API `getAllUsersServices`
5. Add Second function to Add New to API`addUsersServices`

```javascript
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 `
  ```javascript 
// Import Users Services
import UsersManageServices from '@/Services/Users.services'
  ```
2. Add new variable in data Object to store the Data from API
  ```javascript 
   // it will be an empty Array for now
    AllUsers:[],
  ```
3. You Remember our Object `userInfo` who store your data from Inputs
  ```javascript 
   // 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
  ```javascript 
    addUser(){
      UsersManageServices.addUsersServices(this.userInfo).then(res => {
        console.log('Added Success')
      }).catch((error) => {
        console.error(error)
      })
    }
  ```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trxmfzj597ingxqos6ps.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2baz7dryr0enc8xojmwo.PNG)

5. 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
```javascript
  // Get All User 
    getAllUser(){
      UsersManageServices.getAllUsersServices().then(res => {
        this.AllUsers = res.data
      }).catch((error) => {
        console.error(error)
      })
    },
```

6. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abs5pckl16g9do718i7u.png)
 our Table will be like That
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7ucl0pc9cs1rs5hy5qw.png)
 

#Finally the Form and User Information will be like 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llqy7puyq793vjzqdxnk.png)

#### 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 😍