ThinkPHP5 另类方法实现分页功能

前言

当然是自己需要这个功能啦。。。

准备

我所用的前端框架是老外用BootStrap4二开的主题,叫MaterialPro(以下简称MP),我会在本文末附上压缩包。非常好用哦。

传统的分页是使用ul li来做,但是最大的问题就是如果没有正好的样式,那么你还得费大半天时间去写样式,烦得很。所以我这次使用的是MP的按钮组,美观也好看。

实现方法

分页实现是用的TP5自带的paginate方法,在Model里查询数据的时候直接使用该方法进行分页。然后将对象返回过来就好。

注意:官方文档写的是使用render方法来分页,但是在这里我们不用这个方法,因为他在我这有各种BUG。

将数据对象返回过来之后,var_dump之后结构是这样的(这里只发出来跟分页有关的数据结构)

protected 'currentPage' => int 1
  protected 'lastPage' => int 1
  protected 'total' => int 4
  protected 'listRows' => int 10
  protected 'hasMore' => boolean false
  protected 'options' =>
    array (size=6)
      'var_page' => string 'page' (length=4)
      'path' => string '/index/index/charge' (length=19)
      'query' =>
        array (size=0)
          empty
      'fragment' => string '' (length=0)
      'type' => string 'bootstrap' (length=9)
      'list_rows' => int 15
  protected 'nextItem' => null

提示:这里很多人会误认为total是总页数,其实是错误的,total是数据总条数。

接下来就是前端了,很easy,我直接把代码贴上来你们读一下就懂了

<div class="float-right">
{if $record->currentPage()>1}
<button id="pre" type="button" class="btn btn-secondary" data-page="/index/index/charge?page={$record->currentPage()-1}">上一页</button>
{/if}
<div class="btn-group" role="group">
{for start="1" end="$record->lastPage()+1" name="page"}
<button type="button" class="pages btn {if $page==$record->currentPage()}btn-info{else /}btn-secondary{/if}" data-page="/index/index/charge?page={$page}">{$page}</button>
{/for}
</div>
{if $record->currentPage()<$record->lastPage()}
<button id="af" type="button" class="btn btn-secondary" data-page="/index/index/charge?page={$record->currentPage()+1}">下一页</button>
{/if}
</div>
<!--这里写分页代码-->

以及js代码

$('#pre').on('click',function () {
window.location.href = $(this).attr('data-page');
});
$('#af').on('click',function () {
window.location.href = $(this).attr('data-page');
});
$('.pages').on('click',function () {
window.location.href = $(this).attr('data-page');
});

最终效果图:

第一页的时候上一页会隐藏,最后一页的时候下一页会隐藏。很NICE

结尾

怎么样,是不是非常easy......

版权声明:
作者:zjh4473
链接:https://blog.zixutech.cn/?p=170
来源:紫旭Blog
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>