How to implement server-side pagination in Vue.js with Node.js

How to implement server-side pagination in Vue.js with Node.js

This is a simple example of how to implement server-side pagination in Vue.js with a Node.js backend API.

Originally published at https://jasonwatmore.com
This is a simple example of how to implement pagination in Vue.js with a Node.js backend API.

The example contains a hard coded array of 150 objects split into 30 pages (5 items per page) to demonstrate how the pagination logic works. Styling of the example is done with Bootstap 4.

The tutorial code is available on GitHub at https://github.com/cornflourblue/vue-node-server-side-pagination.

Here it is in action (may take a few seconds for the container to startup):

(See on CodeSandbox at https://codesandbox.io/s/vuejs-node-server-side-pagination-example-0l40x)

Running the Vue.js + Node Pagination Example Locally
  1. Install NodeJS and NPM from https://nodejs.org.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/vue-node-server-side-pagination.
  3. Install required npm packages of the backend Node API by running the npm install command in the /server folder.
  4. Start the backend Node API by running npm start in the /server folder,
  5. this will start the API on the URL http://localhost:4000.
  6. Install required npm packages of the frontend Vue.js app by running the npm install command in the /client folder.
  7. Start the Vue.js frontend app by running npm start in the /client folder,
  8. this will build the app with webpack and automatically launch it in a
  9. browser on the URL http://localhost:8080.
Server-Side (Node.js) Pagination Logic

Pagination is handled by the backend Node API with the help of the jw-paginate npm package, for more info on how the pagination logic works see JavaScript - Pure Pagination Logic in Vanilla JS / TypeScript.

Below is the code for the paged items route (/api/items) in the node server file (/server/server.js) in the example, it creates a hardcoded list of 150 items to be paged, in a real application you would replace this with real data (e.g. from a database). The route accepts an optional page parameter in the url query string, if the parameter isn't set it defaults to the first page.

The paginate() function is from the jw-paginate package and accepts the following parameters:

  • totalItems (required) - the total number of items to be paged
  • currentPage (optional) - the current active page, defaults to the first page
  • pageSize (optional) - the number of items per page, defaults to 10
  • maxPages (optional) - the maximum number of page navigation links to display, defaults to 10

The output of the paginate function is a pager object containing all the information needed to get the current pageOfItems out of the items array, and to display the pagination controls in the Vue.js frontend, including:

  • startIndex - the index of the first item of the current page (e.g. 0)
  • endIndex - the index of the last item of the current page (e.g. 9)
  • pages - the array of page numbers to display (e.g. [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ])
  • currentPage - the current active page (e.g. 1)
  • totalPages - the total number of pages (e.g. 30)

I've set the pageSize to 5 in the CodeSandbox example above so the pagination links aren't hidden below the terminal console when the container starts up. In the code on GitHub I didn't set the page size so the default 10 items are displayed per page in that version.

The current pageOfItems is extracted from the items array using the startIndex and endIndex from the pager object. The route then returns the pager object and current page of items in a JSON response.

// paged items route
app.get('/api/items', (req, res, next) => {
   // example array of 150 items to be paged
   const items = [...Array(150).keys()].map(i => ({ id: (i + 1), name: 'Item ' + (i + 1) }));

   // get page from query params or default to first page
   const page = parseInt(req.query.page) || 1;

   // get pager object for specified page
   const pageSize = 5;
   const pager = paginate(items.length, page, pageSize);

   // get page of items from items array
   const pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);

   // return pager object and current page of items
   return res.json({ pager, pageOfItems });
});

Client-Side (Vue.js) Pagination Component

Since the pagination logic is handled on the server, the only thing the Vue.js client needs to do is fetch the pager information and current page of items from the backend, and display them to the user.

Vue.js Home Page Component

Below is the Vue home page component (/client/src/home/HomePage.vue) from the example. The template renders the current page of items as a list of divs with the v-for directive, and renders the pagination controls using the data from the pager object. Each pagination link sets the page query parameter in the url with the <router-link> component and :to="{ query: { page: ... }}" property.

The Vue component contains a watcher function on the page url query parameter '$route.query.page', the handler function is triggered by Vue whenever the page variable in the url querystring changes, the immediate: true flag tells Vue to also run the function when the component first loads. The watcher function checks if the page has changed and fetches the pager object and pageOfItems for the current page from the backend API with an HTTP request.

The CSS classes used are all part of Bootstrap 4.3, for more info see https://getbootstrap.com/docs/4.3/getting-started/introduction/.

<template>
   <div class="card text-center m-3">
       <h3 class="card-header">Vue.js + Node - Server Side Pagination Example</h3>
       <div class="card-body">
           <div v-for="item in pageOfItems" :key="item.id">{{item.name}}</div>
       </div>
       <div class="card-footer pb-0 pt-3">
           <ul v-if="pager.pages && pager.pages.length" class="pagination">
               <li :class="{'disabled':pager.currentPage === 1}" class="page-item first-item">
                   <router-link :to="{ query: { page: 1 }}" class="page-link">First</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === 1}" class="page-item previous-item">
                   <router-link :to="{ query: { page: pager.currentPage - 1 }}" class="page-link">Previous</router-link>
               </li>
               <li v-for="page in pager.pages" :key="page" :class="{'active':pager.currentPage === page}" class="page-item number-item">
                   <router-link :to="{ query: { page: page }}" class="page-link">{{page}}</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === pager.totalPages}" class="page-item next-item">
                   <router-link :to="{ query: { page: pager.currentPage + 1 }}" class="page-link">Next</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === pager.totalPages}" class="page-item last-item">
                   <router-link :to="{ query: { page: pager.totalPages }}" class="page-link">Last</router-link>
               </li>
           </ul>
       </div>
   </div>
</template>

<script>
export default {
   data () {
       return {
           pager: {},
           pageOfItems: []
       }
   },
   watch: {
       '$route.query.page': {
           immediate: true,
           handler(page) {
               page = parseInt(page) || 1;
               if (page !== this.pager.currentPage) {
                   fetch(`/api/items?page=${page}`, { method: 'GET' })
                       .then(response => response.json())
                       .then(({pager, pageOfItems}) => {
                           this.pager = pager;
                           this.pageOfItems = pageOfItems;
                       });
               }
           }
       }
   }
}
</script>

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.