怎样自己去封装一个公共的分页器呢
最近新公司做项目的时候遇到的一个问题,我们在做表格数据展示的时候涉及到分页器,一开始我们用的是element UI的分页器,但是与UI的样式要求不符,和她那边的规格有出入,然后就自己就尝试写了一个(其实以前也写过一个,但是已经忘记,这次想着记录一下心得)。
UI图
在做这类问题之前要先有一个思路,其实这个分页器大致分为两部分,左边的下拉选择部分和右边的分页器部分,只要右边解决了基本上就没啥问题了。
分页器主要分为四种展示场景
直接展示
computed: {
// 总页数
totalPages() {
// 总条数除当前分页数,向上取整
let num = this.total / this.currentSize;
return Math.ceil(num);
},
allPages() {
// 当前页
const c = this.currentPage;
const t = this.totalPages;
if (t < 10) {
// 页数不多直接返回总页数
return t;
}
}
}
后省略
computed: {
// 总页数
totalPages() {
// 总条数除当前分页数,向上取整
let num = this.total / this.currentSize;
return Math.ceil(num);
},
allPages() {
// 当前页
const c = this.currentPage;
const t = this.totalPages;
if (t < 10) {
// 页数不多直接返回总页数
return t;
}
if (c <= 5) {
return [1, 2, 3, 4, 5, 6, 7, 8, '...', t];
}
}
}
前省略
allPages() {
const c = this.currentPage;
const t = this.totalPages;
if (t < 10) {
return t;
}
if (c <= 5) {
return [1, 2, 3, 4, 5, 6, 7, 8, '...', t];
} else if (c >= t - 4) {
return [1, '...', t - 7, t - 6, t - 5, t - 4, t - 3, t - 2, t - 1, t];
}
}
两边省略
allPages() {
const c = this.currentPage;
const t = this.totalPages;
if (t < 10) {
return t;
}
if (c <= 5) {
return [1, 2, 3, 4, 5, 6, 7, 8, '...', t];
} else if (c >= t - 4) {
return [1, '...', t - 7, t - 6, t - 5, t - 4, t - 3, t - 2, t - 1, t];
} else {
return [1, '... ', c - 3, c - 2, c - 1, c, c + 1, c + 2, c + 3, ' ...', t];
}
}
HTML部分,判断当前currentPage来加当前选中的样式,上一页判断currentPage是否等于1来加一个禁止点击的悬浮样式,下一页判断currentPage 是否等于总页数来加一个禁止点击的悬浮样式
<div class="right-part">
<i
:class="['el-icon-arrow-left', currentPage == 1 ? 'prohibit' : '']"
@click="lastPage"
></i>
<div class="selector">
<div
v-for="val in allPages"
:key="val"
:class="['page-item',currentPage == val ? 'actived': '']"
@click.stop="selectPage(val)"
>
{{val}}
</div>
</div>
<i
:class="['el-icon-arrow-right',currentPage == totalPages ? 'prohibit' : '']"
@click="nextPage"
></i>
<div class="current-page">
<el-input
v-model="searchPage"
placeholder=""
type='number'
@keydown.enter.native="jumpPage"
></el-input>
<span class="total-pages">/{{totalPages}}</span>
</div>
<el-button @click="jumpPage">跳转</el-button>
</div>
.page-item {
width: 32px;
height: 32px;
line-height: 32px;
border-radius: 2px;
margin-left: 8px;
cursor: pointer;
&:hover {
color: #1367da;
}
&.actived {
color: #1367da;
}
}
i {
&.prohibit {
cursor: not-allowed;
color: #333333;
}
}
然后可以根据自己需要加一些点击事件,这个就看个人需要了
最终结果
第一次写这个,写出一遍能看的文章,感觉挺麻烦的呀 ε=(´ο`*)))唉。