最近在用vue做博客,要实现一个文章的分页效果,做出来后,顺便记录一下实现的思路,
先看一下效果:
-
第一页时,prev箭头不显示,最后一页时next箭头不显示,随着当前分页的不同,渲染不同的文章列表
-
需要定义下面几个变量:
currentPage: 1, ,默认是1,表示当前所在的页码
totalPage: 1, 默认是1,表示总共有多少页
currentArticleList: [], 当前页的文章列表
totalArticleList:[],全部的文章列表
count:5, 每页显示的文章数量 -
其中totalPage = totalArticleList / count, 然后在进行向上取整,比如说你有6篇文章,count为5,6/5 = 1.2,取整后就是totalPage两页
-
实现的大概思路就是每次点击prev或者next时,吧上一次的currentArticleList清空,然后从totalArticleList吧当前页对应的博客push到currentArticleList数组里面,使用v-for循环进行渲染
methods里面有三个函数:
- initPageList(),在页面初始化(mounted钩子函数)的时候调用:
initPageList() {
for(let i = (this.currentPage-1)*this.count; i < this.currentPage*this.count; i++) {
if(this.totalArticleList[i]) {
this.currentArticleList.push(this.totalArticleList[i])
}
}
},
这里需要理解一下:currentPage默认是1,初始化的时候就向 this.currentArticleList数组里面push 5篇文章, 当currentPage是2,就从第5篇博客一直push到第9篇博客
2. changePageListPrev(),点击prev时触发
changePageListPrev() {
if(this.currentPage > 1) {
this.currentPage--; //点击后当前页码减一
this.currentArticleList = []
for(let i = (this.currentPage-1)*this.count; i < this.currentPage*this.count; i++) {
if(this.totalArticleList[i]) {
this.currentArticleList.push(this.totalArticleList[i])
}
}
}
},
- changePageListNext(),点击next时触发
changePageListNext() {
if(this.currentPage < this.totalPage) {
this.currentPage++; //点击后当前页码加一
this.currentArticleList = []
for(let i = (this.currentPage-1)*this.count; i < this.currentPage*this.count; i++) {
if(this.totalArticleList[i]) {
this.currentArticleList.push(this.totalArticleList[i])
}
}
}
},
html代码如下:
<article style="width:100%">
<div class="articleList">
<div class="article" v-for="(item, index) in currentArticleList" :key="index">
<div class="articleDetail">
<div class="acticleName"><h1>{{item.articleName}}</h1></div>
<hr class="hr">
<div class="acticleTitle"> <p>{{item.articleTitle}}</p></div>
</div>
</div>
</div>
</article>
<div class="pagination">
<span class="prev " @click="changePageListPrev" v-show="currentPage!=1"><i class="iconfont-sm" style="color: #428bca;"></i></span>
<span style="color:rgba(124, 122, 122, 0.8);">{{this.currentPage}} / {{this.totalPage}}</span>
<span class="next " @click="changePageListNext" v-show="currentPage!=totalPage" ><i class="iconfont-sm" style="color: #428bca;"></i></span>
</div>
如果对你有帮助,顺手点个赞吧~ 😃