效果
- 首页
- 第二页
- 第五页
- 最后一页
样式由bootstrap提供
组件
Vue.component('pagination',{
data(){
return {
pageCount:0,pageRange:[0],
};
},
props:[
'total','index','limit','pagerang'
],
methods:{
jumpTo:function(val){
if (this.pageCount >0 && val >= this.pageCount || val < 0 || this.index == val){
return
}
this.index = val;
this.$emit('jump',val);
},
getPageRange:function() {
if (this.pageCount<6){
this.pageRange = [...Array(this.pageCount).keys()];
return
}
let start = 0;
if (this.index > this.pageCount-4){
start = this.pageCount - 5;
}else if (this.index < 2){
start = 0;
}else{
start = this.index -2;
}
this.pageRange = new Array(5);
for (let i=0;i<5;i++){
this.pageRange[i] = start +i;
}
}
},
watch:{
total:function(val) {
this.pageCount = Math.ceil(this.total/this.limit);
this.getPageRange();
},
limit:function(val){
this.pageCount = Math.ceil(this.total/this.limit);
this.getPageRange();
},
index:function(val){
this.getPageRange();
}
},
template:`
<ul class="pagination" style="margin-top: 0%;float: right;" v-if="pageCount>0">
<li class="page-item"><span class="page-link" v-on:click="jumpTo(0)">1</span><li>
<li class="page-item"><span class="page-link" v-on:click="jumpTo(index-1)">«</span><li>
<li class="page-item" v-for="i in pageRange" v-bind:class="{active: index==i}"><span class="page-link" v-on:click="jumpTo(i)">{{i + 1}}</span><li>
<li class="page-item"><span class="page-link" v-on:click="jumpTo(index+1)">»</span><li>
<li class="page-item"><span class="page-link" v-on:click="jumpTo(pageCount-1)">{{pageCount}}</span><li>
</ul>
`
})
usage
html
<pagination :limit="itemLimit" :total="itemCount" :index="currentIndex" v-on:jump="jumpTo"></pagination>
app
methods:{
jumpTo:function(index){
this.pageJumpTo(index);
},
}
总结
total 参数是记录未分页前的所有item数量。监听 jump 事件可获取组件页面跳转目标页数。
后台处理的页码是0n,而前端显示是1n+1,主要是为了后端交互方便。