Datatables with VueJS [ Vuetify + Pagination + Rest API ]
Tags: vue, datatable, pagination, npm
Published: 2020-07-25 18:56:41

In this tutorial, We want to share how we can configure datatable with [VueJS](https://vuejs.org/) using [Vuetify](https://vuetifyjs.com/en/). Additionally here we are configuring datatable to consume paginated REST API.

### Starting with fresh VueJS Project.

1. Creating the VueJS project using Vue CLI.
```shell
$ vue create datatable-vue
```
Here I'm using default **(babel, eslint)**  as the preset. You can use any other preset you wish to use. 
```curl
$ cd datatable-vue
```
Ok now we have a fresh VueJS project with basic components. You can run this app using the following command. Or else just skip to the next phase where we are adding vuetify component library into the Vue project. 

```shell
$ npm run serve
```
### Configuring Vuetify with VueJS.

Ok, Let's add vuetify component library into our fresh Vue js project. There are many ways which you could do this phase, Here I'm using the simplest way and If you need more information please refer to this [Quick Start Guide.](https://vuetifyjs.com/en/getting-started/quick-start/) 

```shell
$ vue add vuetify
```
Ok, now we have VueJS project configured to use vuetify components. Let's start the implementations on Datatables. 

Here we are using the third party [fake API with pagination](https://instantwebtools.net/fake-rest-api) to integrate with datatables. This API is hosted and open to consume for free. There are many API endpoints that cover all the HTTP methods.

For this tutorial, we are getting pagination enabled API endpoint.

```shell
https://api.instantwebtools.net/v1/passenger?size=10&page=0
```

### Configring Vue-Axios.

To consume the API we are using vue-axios [A small wrapper for integrating axios to Vuejs](https://www.npmjs.com/package/vue-axios). 

Let's add vue-axios to our VueJS project by.

```shell
$ npm install --save axios vue-axios
```
and then edit the entry file in your project with following

```javascript
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)
```
### Configuring Datatable to consume API.

Now we are ready to consume our API and read the data. So the only pending thing is config datatables to show those paginated data set. 

To do this you can clear your current HelloWorld component or else create a new component and load it on the root page. Here we've created a new component and used it in the App.vue file.

Just create a new file naming 'DatatableComponent.vue' in the components folder. Here you can use any name you prefer. Then add the following code snippet where it will create the basic UI of the Datatable view. 

```html
<template>
  <div class="">
    <h1 style="text-align: center;">Datatable with 3rd Party API</h1>
    <v-data-table
      :page="page"
      :pageCount="numberOfPages"
      :headers="headers"
      :items="passengers"
      :options.sync="options"
      :server-items-length="totalPassengers"
      :loading="loading"
      class="elevation-1"
    >
      <template v-slot:item.logo="{ item }">
        <img :src="item.airline.logo" style="width: 10%;" />
      </template>
      <template v-slot:item.website="{ item }">
        <a :href="item.airline.website">{{ item.airline.website }}</a>
      </template>
    </v-data-table>
  </div>
</template>
```
Here we are using page, pageCount, headers, items, server-items-length to inject pagination data set. you can find more details about available params to inject with datatables from [here](https://vuetifyjs.com/en/components/data-tables/). 

After that add the following javascript code into the script section. Here we have commented on basic functionality and what's happening. 

```javascript

import axios from "axios";
export default {
  name: "DatatableComponent",
  data() {
    return {
      page: 0,
      totalPassengers: 0,
      numberOfPages: 0,
      passengers: [],
      loading: true,
      options: {},
      headers: [
        { text: "Passenger Name", value: "name" },
        { text: "Number Of Trips", value: "trips" },
        { text: "Airline", value: "airline[0].name" },
        { text: "Logo", value: "logo" },
        { text: "Website", value: "website" },
      ],
    };
  },
  //this one will populate new data set when user changes current page. 
  watch: {
    options: {
      handler() {
        this.readDataFromAPI();
      },
    },
    deep: true,
  },
  methods: {
    //Reading data from API method. 
    readDataFromAPI() {
      this.loading = true;
      const { page, itemsPerPage } = this.options;
      let pageNumber = page - 1;
      axios
        .get(
          "https://api.instantwebtools.net/v1/passenger?size=" +
            itemsPerPage +
            "&page=" +
            pageNumber
        )
        .then((response) => {
          //Then injecting the result to datatable parameters.
          this.loading = false;
          this.passengers = response.data.data;
          this.totalPassengers = response.data.totalPassengers;
          this.numberOfPages = response.data.totalPages;
        });
    },
  },
  //this will trigger in the onReady State
  mounted() {
    this.readDataFromAPI();
  },
};
```
Then import this newly created component to App.vue and let's run the app. To do that just introduce and add new components. This is our sample App.vue file.

```javascript
import DatatableComponent from './components/DatatableComponent';

export default {
  name: 'App',

  components: {
    DatatableComponent,
  },

  data: () => ({
    //
  }),
};
```
```html
<v-main>
 <DatatableComponent/>
</v-main>
```

All done!!! Let's start the server and check our newly built Datatable with VueJS.

![Datatable-with-vuejs-Vuetify-axios](https://i.ibb.co/bmnJZNd/Datatable-with-vuejs-Vuetify-axios.png)

Thanks for reading our first post on dev.to and you can find full source code from our [GitHub](https://github.com/instantwebtools-net/tutorials/tree/master/datatable-pagination-with-api-vue-js/app). 

Further Readings,

[Vue JS CRUD with Vuetify, Axios, Spring Boot REST API](https://javatodev.com/vue-js-crud-with-vuetify/)
[Angular 10 CRUD with Spring Boot REST API](https://javatodev.com/angular-10-crud-with-spring-boot-rest-api/)