For reusability, pagination logic should be in a separated component
The parent component (where pagination is included) should not be handling any pagination logic, except displaying data according to current page
Component
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
name:'pagination',props:{total:{type:Number,default:0},},data(){return{elements:[],// store pages object to be rendered
totalPages:0,// total pages
current:1,// current page
itemsPerPage:10,// self-explanatory
pageCount:5// how many pages you want to display
}},
Most of the properties are pretty self-explanatory, except pageCount. It’s total pages which we show to user.
methods:{add(s,f){for(vari=s;i<=f;i++){this.elements.push({type:'page',page:i})}},addBreak(){this.elements.push({type:'ellipse-break'});},first(){// Add first page
this.elements.push({type:'page',page:1});},last(){// Add last page
this.elements.push({type:'page',page:this.totalPages},)},...}
Explanation:
add: simply creating a new page and add it to elements. For example, add(1,5) will create 5 page buttons.
methods:{...paginate(){this.elements=[];this.totalPages=Math.ceil(this.total/this.itemsPerPage);lett=Math.floor(this.pageCount/2);if(this.totalPages<t){// Case without any breaks
this.add(1,this.totalPages);}elseif(this.current>=this.totalPages-t){// Case with breaks at beginning
this.first();this.addBreak();this.add(this.current-t,this.totalPages);}elseif(this.current<=t+1){// Case with breaks at end
this.add(1,this.current+t);this.addBreak();this.last();}else{// Case with breaks at beginning and end
this.first();this.addBreak();this.add(this.current-t,this.current+t);this.addBreak();this.last();}},onChange:function(page){this.current=page;this.paginate();letfrom=(this.current*this.itemsPerPage)-this.itemsPerPage;letto=(this.current*this.itemsPerPage);this.$emit('showPagingData',{from:from,to:to});}}
Explanation:
onChange: called when user clicked on page button. Here we calculate the records we have to show on clicked page, then emit an event to parent component.
paginate: this method will be called every time we need to calculate and render paging (after search, user clicked on page buttton etc). There are 4 cases we need to check:
total pages < number of pages we want to display
current page is near the end, so we have to add break at the beginning
current page is near the beginning, so we have to add break at the end
current page is kinda in the middle, so we have to add break at both the beginning and the end