loading...

Datatables with VueJS [ Vuetify + Pagination + Rest API ]

instantwebtoolsnet profile image Instant Web Tools ・3 min read

In this tutorial, We want to share how we can configure datatable with VueJS using Vuetify. Additionally here we are configuring datatable to consume paginated REST API.

Starting with fresh VueJS Project.

  1. Creating the VueJS project using Vue CLI.
$ vue create datatable-vue

Here I'm using default (babel, eslint) as the preset. You can use any other preset you wish to use.

$ 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.

$ 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.

$ 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 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.

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.

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

$ npm install --save axios vue-axios

and then edit the entry file in your project with following

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.

<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.

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


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.

import DatatableComponent from './components/DatatableComponent';

export default {
  name: 'App',

  components: {
    DatatableComponent,
  },

  data: () => ({
    //
  }),
};
<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

Thanks for reading our first post on dev.to and you can find full source code from our GitHub.

Discussion

pic
Editor guide