How to create a reporting app with Vue 3 and Composition API?


Vue is a JavaScript framework that allows developers to create web applications. It is mainly used to build single-page web applications. There are lots of benefits to using the vue to create web applications, such as easy structure, lightweight, component-based architecture, etc.

Before we start with the tutorial, let’s learn about the reporting app and composition API.

The reporting app is a single or multiple-page web application that displays useful data in a proper format, such as table format. It is used to show the reports of the data in a particular format.

The composition API allows developers to code based on logic instead of life cycles. We can create more maintainable and modular code in the vue application.

Now, we will use the ‘https://jsonplaceholder.typicode.com/posts’ API to get data and format all data in the table in the vue application.

Users should follow the steps below to start creating a vue application.

  • Step 1 − In the first step, users require to install the vue on the local computer. Open the terminal and execute the below command.

npm install -g @vue/cli
  • Step 2 − Now, enter the below command in the terminal to start the vue application. Here, ‘reporting-app’ is an application name.

npx vue create reporting-app
  • Step 3 − We have created the vue app successfully. Now, run the below command in the terminal to move into the project directory.

cd reporting-app
  • Step 4 − Next, we require to install the required dependencies in the vue application by executing the below command in the terminal.

npm install axios vue-router

We installed the axios to make an API request and vue-router to handle the routing of the application.

  • Step 5 − Now, create a ‘router.js’ file in the ‘src’ project directory. After that, add the below code in the file.

Filename – router.js

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from './views/HomeView.vue'
import ReportTable from './views/ReportTable.vue'
const routes = [{
      path: '/',
      name: 'home',
      component: HomeView
   },{
      path: '/report',
      name: 'report',
      component: ReportTable
   }
]
const router = createRouter({
   history: createWebHistory(),
   routes
})
export default router

We imported the HomeView and ReportTable components from the above code from the related file. After that, we have created the ‘/’ and ‘/report’ routers, and exported them.

  • Step 6 − In the ‘main.js’ file set up the router configuration for the application. Add the below code in the main.js file.

Filename – main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')

In the above code, we have imported the router component and used it with the app using the app.use() method.

  • Step 7 − Next, we require to set up the ‘App.vue’ file to show the particular component based on the router. Add the below content into the App.vue file.

Filename – App.vue

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from './views/HomeView.vue'
import ReportTable from './views/ReportTable.vue'
const routes = [{
      path: '/',
      name: 'home',
      component: HomeView
   },{
      path: '/report',
      name: 'report',
      component: ReportTable
   }
]
const router = createRouter({
   history: createWebHistory(),
   routes
})
export default <template>
   <div id="app">
      <router-view />
   </div>
</template>
<script>
   export default {
      name: "App",
   };
</script>
  • Step 8 − Now, we will create components to render on the web page. First, create the ‘views’ folder in the ‘src’ directory, and create the ‘homeview.vue’ file inside that.

After that, add the below code in the file.

Filename – Homeview.vue

<template>
   <div>
      <h1> Home </h1>
   </div>
</template>
<script>
   export default {
     name: 'HomeView'
   }
</script>

In the above code, we render the ‘Home’ on the web page.

  • Step 9 − Now, we need to create ReportTable.vue component in the ‘views’ directory. After that, add the below code in the file.

Filename – ReportTable.vue

<template>
   <div class = "report">
      <h1 class = "report-heading"> Report </h1>
      <!-- Creating the table -->
      <table class = "report-table">
         <thead>
            <tr>
               <th> User ID </th>
               <th> ID </th>
               <th> Title </th>
               <th> Body </th>
            </tr>
         </thead>
         <tbody>
            <!-- Iterating through the reports and showing every report one by one -->
            <tr v-for = "report in state.reports" :key = "report.id">
               <td> {{ report.userId }} </td>
               <td> {{ report.id }} </td>
               <td> {{ report.title }} </td>
               <td> {{ report.body }} </td>
            </tr>
         </tbody>
      </table>
   </div>
</template>
<script>
   import { reactive, onMounted } from "vue";
   import axios from "axios";
   export default {
      setup() {
         // using the composition API
         const state = reactive({
            reports: [],
         });
         // fetching data on the mount, and storing response in the reports array
         onMounted(() => {
            axios
            .get("https://jsonplaceholder.typicode.com/posts")
            .then((response) => {
            state.reports = response.data;
            })
            .catch((error) => {
               console.log(error);
            });
         });
         return { state };
      },
   };
</script>
<style>
   /* Styling the table */
   .report {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      font-family: Arial, sans-serif;
      color: #333;
   }
   .report-heading {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 20px;
      text-align: center;
   }
   .report-table {
      width: 100%;
      border-collapse: collapse;
   }
   .report-table th {
      background-color: #333;
      color: #fff;
      padding: 10px;
      text-align: left;
      font-size: 18px;
   }
   .report-table td {
      background-color: #f5f5f5;
      padding: 10px;
      font-size: 16px;
   }
   .report-table tr:hover {
      background-color: #ddd;
   }
</style>

In the above code, we used the composition API's ‘reactive’ function to create a reactive state object containing the ‘reports’ array.

We used the ‘onMount()’ method to fetch the data from the API using the axios whenever the component mounts on the web page. After that, we store the response in the reports array and return the state object.

We created the table to represent the data in the template code. After that, we access the reports array from the states object and use for loop to loop through all data and show them in the table row. Also, we have styled the table.

Here, users can observe that we haven’t used the component life cycles to update the data, as we have used the composition API to make the state object reactive. So, whenever a response from API updates, it will rerender data automatically.

  • Step 10 − Execute the below command in the project directory to run the project.

npm run serve

Now, users should open the http://192.168.110.33:8080/report URL to see the API data in the table format. It will show the output shown below.

Users learned to use the composition API’s features in this tutorial. As discussed above, when we use the composition API, we don’t require to deal with the lifecycles, as we can use the ‘reactive()’ function to make variables or objects reactive. Also, users can try the composition API with the updating data and observe how it re-renders the web page whenever reactive variables update.

Updated on: 04-May-2023

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements