Pagination in Vue.js
Pagination enhances UX by allowing users to visualize data in smaller chunks, or pages. Here’s how to go about making a Vue.js component with pagination that allows us to only view parts of our data at a time.
The only local data I need is the page number.
pageNumber: 0 // default to page 0
For props, passing the data is a must, but I’ll also take a size argument for the max number of records.
For my methods, I’ll use methods to go to the previous and next pages:
A quick computed property to figure out how many pages there are:
let l = this.listData.length,
s = this.size;
paginatedData computed property is where it comes together. This is the filtered data that will be rendered.
const start = this.pageNumber * this.size,
end = start + this.size;
return this.listData.slice(start, end);
Edit: I was initially doing something funky to copy the array while using
.slice is the better approach. Thanks Alexander Karelas.
And for the template:
<li v-for="p in paginatedData">
I want to prevent the buttons from working when they should. For the
prevPage button, I will add
:disabled="pageNumber==0" and for the
nextPage button, I will add
:disabled="pageNumber >= pagecount -1".
A working demo of my component:
It can be easy to overthink things sometimes, but pagination is a straightforward feature that we can offer to our users without a lot of effort.
Thanks for reading!
Denny Headrick is a web developer for the USAF that likes his work way too much. On top of developing on a variety of platforms and with Vue.js when he can, he likes to blog occasionally. You can follow him on Twitter at @dennythecoder.