分页器已知前提(4个条件/父组件传值):
pageNo当前页,pageSize每页需展示多少条,total 总条数,continues分页器连续页码数
一、创建组件,在components下创建(公用组件)
<template>
<div class="pagination">
<button :disabled="pageNo==1" @click="changePage(pageNo-1)" >上一页</button>
<button v-if="pageNo>3" @click="changePage(1)" :class="{active:pageNo==1}">1</button>
<button v-if="pageNo>3">···</button>
<button v-for="(page,index) in startNumAndEndNum.end" :key="index"
v-show="startNumAndEndNum.start<=page" @click="changePage(page)"
:class="{active:pageNo==page}">{{ page }}</button>
<button v-show="pageNo<=(totalPage-continues/2)">···</button>
<button v-show="pageNo<=(totalPage-continues/2)"
@click="changePage(totalPage)" :class="{active:pageNo==totalPage}">{{ totalPage }}</button>
<button :disabled="pageNo>=totalPage" @click="changePage(page+1)">下一页</button>
<button style="margin-left: 30px">共 {{ total }} 条</button>
</div>
</template>
<script>
export default {
name: "Pagination",
props: ["pageNo", "pageSize", "total", "continues"],
computed: {
totalPage() {
return Math.ceil(this.total / this.pageSize);
},
startNumAndEndNum() {
const { pageNo, totalPage, continues } = this;
let start = 0;
let end = 0;
if (continues > totalPage) {
start = 1;
end = totalPage;
} else {
let leftNum = pageNo - parseInt(continues / 2);
let rightNum = pageNo + parseInt(continues / 2);
if(leftNum<=1){start=1;end=continues}
else if(rightNum>=totalPage){start=totalPage-continues;end=totalPage}
else{start=leftNum,end=rightNum}
return { start, end };
}
},
},
methods:{
changePage(page){this.$emit('getPageNo',page)}
}
};
</script>
<style lang="scss" scoped>
.pagination {
text-align: center;
margin: 40px 0;
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;
&[disabled] {
color: #c0c4cc;
cursor: not-allowed;
}
&.active {
cursor: not-allowed;
background-color: #409eff;
color: #fff;
}
}
}
</style>
二、在main.js中全局注册
//引用
import Pagination from '@/components/Pagination'
//全局注册
Vue.component(Pagination.name,Pagination)
三、父组件中,vc 实例化 并传值
<!-- 分页器 -->
<Pagination
:pageNo="searchParmas.pageNo"
:pageSize="searchParmas.pageSize"
:total="total"
:continues="5"
@getPageNo="getPageNo"></Pagination>