Home > Article > Web Front-end > Using pagination in Vue
The pagination feature enhances the user experience by allowing users to visualize data in smaller chunks or pages. Here's how to create a Vue.js component with pagination so that we can only view part of the data at a time.
I'll start by going through our JavaScript objects one by one and then display the template.
The only local data I need is the page number.
data(){ return { pageNumber: 0 // default to page 0 } }
For props, data is necessary. In addition, I also defined the size parameter to save the maximum amount of data on each page.
props:{ listData:{ type:Array, required:true }, size:{ type:Number, required:false, default: 10 } }
In methods, I defined two methods for the next page and the previous page:
methods:{ nextPage(){ this.pageNumber++; }, prevPage(){ this.pageNumber--; } }
I use the calculated attribute value to calculate how many pages there are in total:
pageCount(){ let l = this.listData.length, s = this.size; return Math.floor(l/s); }
paginatedData is to get the calculated attribute of the filtered data:
paginatedData(){ const start = this.pageNumber * this.size, end = start + this.size; return this.listData.slice(start, end); }
Modification: At the beginning I used .splice to copy the array, but a more perfect way is to use the .slice method, thank Alexander Karelas here.
In the template:
<div> <ul> <li v-for="p in paginatedData"> {{p.first}} {{p.last}} {{p.suffix}} </li> </ul> <button @click="prevPage"> Previous </button> <button @click="nextPage"> Next </button> </div>
I hope to prevent the user from pressing the button at the beginning or end. For the prevPage button, I added: disabled="pageNumber=0" and for the nextPage button. , I added: disabled="pageNumber >= pagecount -1".
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Using pagination in Vue. For more information, please follow other related articles on the PHP Chinese website!