Using jQuery DataTables with Axios and Vue.js

I was doing a asp.net core application where I need to implement CRUD razor pages. I was able to implement easily with the default scaffolding of asp.net core, but since there are more than 20000 rows the loading time for the list screen was high and it takes some seconds to convert the table to jQuery datatables from document.ready().

So, I decide to load the data from WEBAPI using some client side technology. I had done it using jQuery many times .so I decide to give Vue.js a try

Please find the steps below to implement jQuery data tables in vue .js using ajax/axios, I will show it using a simple HTML page instead of razor pages to avoid complexity

 

  1. Create a simple html page

 <html>

<head>

    <title>JQuery DataTables in Vue.js using axios/remote data </title>

</head>

<body>

    <table id="tbllist" class="table">

        <thead></thead>

        <tbody></tbody>      

    </table>

</body>

</html>

 

  1. Add the necessary libraries
  • JQuery
  • Bootstrap 4
  • Vue.js
  • Axios (Promise based HTTP client for the browser and node.js)
  • jQuery DataTables 

  I used CDN for all of the above from , you can use any of the package installer like nuget or npm

 <html>

<head>

    <title>JQuery DataTables in Vue.js using axios/remote data </title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.common.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

 

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" />

</head>

<body>

    <div id="app">

        <table id="tbllist" class="table">

            <thead></thead>

            <tbody></tbody>

        </table>

    </div>

</body>

</html>

 

3.Add Vue Instance to the page

       var app = new Vue({

            el: '#app',

           data: {

               dt: null, // object for  datatable

               list:[]  // object for holding remote data

            },

            mounted() {

              

            },

            created() {

 

            },

            watch: {

              

            },

            methods: {               

            }

        });

Now when the page loads, we need to make an axios call to remote webapi or any restful api and get data

 

  1. Create the Method to call remote data inside methods section

            ShowList: function () {

                    axios(

                        { method: 'get', url: ' https://localhost:44382/api/company.then((response) => {

                            this.dt = $("#tbllist").DataTable();

                            setTimeout(() => this.list = response.data);

                        }).catch((error) => { console.log(error); });

            },

 Call the method in created section

     mounted() {

        this. ShowList ();

      },         

  1. Now add a watch to the “list” to destroy and rebind the datatable on every change 

  watch: {

    list(val) {

      this.dt.destroy();

      this.$nextTick(() => {

        this.dt = $("#tbllist").DataTable();

      })

    }

  },

This is very important. If this is not done Vue will not recognize the DOM changes and table will not be rendered on any datatable events like filter or sort

 

Total Vue instance will look like below

 

       var app = new Vue({

            el: '#app',

           data: {

               dt: null, // object for  datatable

               list:[]  // object for holding remote data

            },

            mounted() {

                this.ShowList();

            },

            created() {

 

            },

            watch: {

             

                    list(val) {

                        this.dt.destroy();

                        this.$nextTick(() => {

                            this.dt = $("#tbllist").DataTable();

                        })

                    }               

            },

            methods: {   

                ///////////////////////////////////////////// Region for Showing List /////////////////////////////////////////////////////////               

                ShowList: function () {

                    axios(

                        { method: 'get', url: '/api/Company' }).then((response) => {

                           

                            this.dt = $("#tbllist").DataTable();

                            setTimeout(() => this.list = response.data);

                        }).catch((error) => { console.log(error); });

            },

            }

        }); 

6.Create the Api returning data as array of object 

Sample Api action implementation (asp.netcore)

// GET: api/Company

            [HttpGet]

            public ActionResult<IEnumerable<Company>> GetCompany()

            {

                 return Ok(_unitOfWork.Company.GetAll());

            }

 

 

Change the table html to show columns

 

        <table id="tbllist" class="table">

            <thead><tr><th>Name</th><th>Address</th><th>Action</th></tr></thead>

            <tbody>

                <tr v-for="(item,i) in list" :key="i">

                    <td>{{ item.companyName  }}</td>

                    <td>{{ item.companyAddress }}</td>

                    <td>

                        <button type="button" class="btn btn-info">Edit</button>

                        <button type="button" class="btn btn-info">View</button>

                    </td>

                </tr>

            </tbody>

        </table> 

Now run the application and check wheather the datatable is loaded (make sure that API has cross site enabled) 

The total html page will look like below

 

<html>

<head>

    <title>JQuery DataTables in Vue.js using axios/remote data </title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.common.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

 

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" />

</head>

<body>

    <div id="app">

        <table id="tbllist" class="table">

            <thead><tr><th>Name</th><th>Address</th><th>Action</th></tr></thead>

            <tbody>

                <tr v-for="(item,i) in list" :key="i">

                    <td>{{ item.companyName  }}</td>

                    <td>{{ item.companyAddress }}</td>

                    <td>

                        <button type="button" class="btn btn-info">Edit</button>

                        <button type="button" class="btn btn-info">View</button>

                    </td>

                </tr>

            </tbody>

        </table>

     

    </div>

    <script>

        var app = new Vue({

            el: '#app',

           data: {

               dt: null, // object for  datatable

               list:[]  // object for holding remote data

            },

            mounted() {

                this.ShowList();

            },

            created() {

            },

            watch: {             

                    list(val) {

                        this.dt.destroy();

                        this.$nextTick(() => {

                            this.dt = $("#tbllist").DataTable();

                        })

                    }               

            },

            methods: {  

                ///////////////////////////////////////////// Region for Showing List /////////////////////////////////////////////////////////              

                ShowList: function () {

                    axios(

                        { method: 'get', url: '/api/Company' }).then((response) => {

                           

                            this.dt = $("#tbllist").DataTable();

                            setTimeout(() => this.list = response.data);

                        }).catch((error) => { console.log(error); });

            },

            }

        });

    </script>

</body>

</html>

 

try this out...

Happy Coding.....................

Sreenath Ganga

 

 

 

 

Other Free Training Materials Available

Free Kerala PSC Exam Training Online
Way4job - Free Kerala PSC training online with previous question papers and free mock exams

Free Kerala PSC training provide notes, Free Online daily Mock test, Previous Questions and answers in english and malayalam. Practice previous years question answers in exam mode will help you success.

Study Now
Free DHA Training
Free DHA Training for Nurses ,Doctors and other medical persons. Sample Questions and Mock test

Study and Practise DHA

Study Now
Free Online PMP Training based on PMBOK
Best Free Online PMP Training based on PMBOK

Best Free Online PMP Training based on PMBOK and PMI guidelines,Sample questions,Exam Simulators and PMP Notes and Flashcards makes you understand the concepts clearly and pass PMP exam at first attempt

Study Now
Free Microsoft Certification Trainings Material
Free Microsoft Training

Study Now

Comments


Commented by : {{x.userName}} {{new Date( x.addedDate).toString().split(' ').splice(0, 5).join(' ') }}

{{x.commentDesc}}

Currently viewing : 145