## 在我们开发过程中都离不开分页器,手写一个分页器能更好的理解分页器的原理,需要知道三个数据,pageNo:当前页数,pageNum:每一页显示多少数(一般都为5或7页,为了美观!!),total:总页数,知道总页数和每一页显示多少页数,我们可以得出一共用多少页
## 代码如下:
<template>
<div>
<div class="pagination">
<button v-show="pageNo!=1" @click="$emit('getPageNo',pageNo-1)">上一页</button>
<button
v-show="startNumAndEndNum.start>1"
@click="$emit('getPageNo',1)"
:class="{active:pageNo==1}"
>
1
</button>
<button v-show="startNumAndEndNum.start>2">···</button>
<button
v-for="(page,index) in startNumAndEndNum.end"
:key="index"
v-if="page>=startNumAndEndNum.start"
@click="$emit('getPageNo',page)"
:class="{active:pageNo==page}"
>{{page}}</button>
<button v-show="startNumAndEndNum.end<totalPage-1">···</button>
<button
v-show="startNumAndEndNum.end<totalPage"
@click="$emit('getPageNo',totalPage)"
:class="{active:pageNo==totalPage}"
>
{{totalPage}}
</button>
<button v-show="pageNo!==totalPage" @click="$emit('getPageNo',pageNo+1)">下一页</button>
<button style="margin-left: 30px">共 {{ total }} 条</button>
</div>
</div>
</template>
<script>
export default {
name: "Pagination",
props:['pageNo','pageSize','total','continue'],
computed:{
//总共多少页
totalPage(){
//Math.ceil()向上取整
return Math.ceil(this.total/this.pageSize)
},
//连续页码的起始页码和结束页码,至少是5页
startNumAndEndNum(){
let start = 0 ,end = 0
//当页码不足5页时
if (this.continue>this.totalPage){
start=1
end=this.totalPage
//正常现象,页码超过5页时
}else {
//Math.floor()向下取整
start=this.pageNo-Math.floor(this.continue/2)
end=this.pageNo+Math.floor(this.continue/2)
if (start<1){
start=1
end=this.continue
}
if(end>this.totalPage){
start=this.totalPage-this.continue+1
end=this.totalPage
}
}
return {start,end}
}
}
}
</script>
<style scoped lang="less">
.pagination {
text-align: center;
button {
margin: 0 5px;
background-color: #f4f4f5;
color: #606266;
outline: none;
border-radius: 2px;
padding: 0 4px;
vertical-align: top;
display: inline-block;
font-size: 13px;
min-width: 35.5px;
height: 28px;
line-height: 28px;
cursor: pointer;
box-sizing: border-box;
text-align: center;
border: 0;
&.active {
background-color: red;
color: #fff;
}
}
}
</style>