ThinkPHP5 另类方法实现分页功能

1,775次阅读
没有评论

共计 1736 个字符,预计需要花费 5 分钟才能阅读完成。

前言

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

准备

我所用的前端框架是老外用 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');
});

最终效果图:

%title插图%num
第一页的时候上一页会隐藏,最后一页的时候下一页会隐藏。很 NICE

结尾

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

正文完
 
紫旭
版权声明:本站原创文章,由 紫旭 2018-10-02发表,共计1736字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)