【Vue】手把手教你用vue.js实现一个分页组件

最近在用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里面有三个函数:
  1. 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])
          }
        }
      }
    },
  1. 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;">&#xe613;</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;">&#xe651;</i></span>
    </div>

如果对你有帮助,顺手点个赞吧~ 😃

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值