从0到1的分页器

SHOYUF

之前写的是手机页的分页,没有使用到数字分页,现在开始使用Vue写单页应用,发现需要一个分页器。 在过去没有写过分页器,对分页器只有展示层面上的认识,现在发现分页器在原理上还是比较复杂的。 在网上找了一圈,发现没有完全符合自己要求的分页器,所以打算自己修改一个使用

网站是根据 Bootstrap 构建的,所以根据 Bootstrap 模板写出 Teamplate

<nav v-if="all > 1" class="text-center">
    <ul class="pagination">
        <li v-if="showFirst"><a @click="myCur--">&laquo;</a></li>
        <li v-for="index in indexes"  :class="{ 'active': myCur == index}">
            <a @click="btnClick(index)">{{ index }}</a>
        </li>
        <li v-if="showLast"><a @click="myCur++">&raquo;</a></li>
        <li><a>共 {{all}} 页</a></li>
    </ul>
</nav>

script部分

export default{
    data(){
        return{
            myCur:1
        }
    },
    props:['all','pageSize'],
    methods:{
        //页码点击事件
        btnClick(index){
            if(index != this.myCur){
                this.myCur = index
            }
        }
    },
    watch:{
        myCur(val){
            this.$emit('page-to', val);
        }
    },
    computed:{
        indexes(){
            var list = [];
            //计算左右页码
            var mid = parseInt(this.pageSize / 2);//中间值
            var left = Math.max(this.myCur - mid,1);
            var right = Math.max(this.myCur + this.pageSize - mid -1,this.pageSize);
            if (right > this.all ) { right = this.all}
            while (left <= right){
                list.push(left);
                left ++;
            }
            return list;
        },
        showLast(){
            return this.myCur != this.all;
        },
        showFirst(){
            return this.myCur != 1;
        }
    }
}

遇到的问题

  1. Vue2 not support two-ways bind. use myCur watcher
  2. Vue2 use $emit replaced $dispatch

以下内容更新于2018年9月

如今写个人博客应用时也遇到了相关问题,现把新方法写出来

需求:

  1. 显示附近五个页码
  2. 不能出现负数或其他非法页码

方案:

/**
   *
   * @param {object} pageInfo - all page info
   * @param {int} pageInfo.currentPage - current page number
   * @param {int} pageInfo.maxPage - max page number
   * @return {array} - page Array
   */
  pageCal(pageInfo) {
    const { currentPage, maxPage } = pageInfo;
    if (maxPage <= 4) {
      const result = [];
      for (let index = 1; index <= maxPage; index++) result.push(index);
      return result;
    }
    if (currentPage <= 2) return [ 1, 2, 3, 4, 5 ];
    if (maxPage - currentPage <= 2) return [ maxPage - 4, maxPage - 3, maxPage - 2, maxPage - 1, maxPage ];
    return [ currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2 ];
  }

本站使用署名 4.0 国际 (CC BY 4.0) 创作共享协议,转载请署名,图片请转存。

提醒:本文最后更新于 2054 天前,文中所描述的信息可能已发生改变,请谨慎使用。

湘ICP备13009407号