DEV Community

Cover image for Vue.js + Node – Server Side Pagination
kishan kumar
kishan kumar

Posted on

Vue.js + Node – Server Side Pagination

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

Server-Side (Node.js) Pagination Logic
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 the parameter in the URL query string if the parameter isn’t set it defaults to the first page.

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

total items (required) – the total number of items to be paged
currentPage (optional) – the currently 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 currently 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.

Read More about About Vue Paginations | Vue js Paginations | Server Side Pagination | Node and Vue Pagination

Top comments (0)