How To Use Async/Await In Vue.js

How To Use Async/Await In Vue.js:

In this article, we will learn how to use async/await in vue.js

Step 1: Create a new Vue project:

vue create async-await-demo

Step 2: Install require packages:

npm i axios bootstrap

Step 3: Open main.js file and add following in it:

import Vue from 'vue'
import App from './App.vue'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Vue.config.productionTip = false


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

Step 4: Open App.vue file and add the following in it:

<template>
  <div id="app"><department></department></div>
</template>
<script>
import Department from './components/Department.vue';
export default { name: 'App', components: { Department } };
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Step 5: Create Department.vue file and add the following in it:

<template>
  <div class="container">
    <div class="card">
      <div class="card-header">
        <h1>Department Details</h1>
      </div>
      <div class="card-body">
        <router-link to="/add" class="btn btn-primary" exact
          >Create</router-link
        >
        <table border="1px" class="table">
          <tr>
            <th>DepartmentId</th>
            <th>DepartmentName</th>
            <th>Delete</th>
          </tr>
          <tr v-for="department in departments" :key="department.id">
            <td>{{ department.departmentId }}</td>
            <td>{{ department.departmentName }}</td>
            <td>
              <button
                class="btn btn-danger"
                v-on:click="deleteDept(department.departmentId)"
              >
                Delete
              </button>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      departments: [],
      apiUrl:'https://localhost:44368/api'
    };
  },
  mounted() {
    this.getAllDepartment();
  },
  methods: {
   async getAllDepartment() {
      await fetch(`${this.apiUrl}/Department/GetAllDepartment`)
        .then((res) => res.json())
        .then((res) => {
          this.departments = res;
        });
    },
   async deleteDept(id) {
      let uri =
        `${this.apiUrl}/Department/DeleteDepartment/id?id=` + id;
      this.departments.splice(id, 1);
      await axios.delete(uri);
      this.getAllDepartment();
    },
  },
};
</script>

<style scoped>
.btn {
  margin: 10px;
}
</style>

Code in action:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories