Day 18 | 常用范例:表格分页 Pagination 前後端做好只需三分钟!?

今天的范例是超级无敌常用,有用到表格就一定会有的 分页(Pagination),从零到有不用三分钟!!!

如果原本是写 Vue 的夥伴,Livewire 可以让你省下超过半小时的时间在处理分页 API 还有页面显示的部分,简直超方便!!

DEMO 页面
GitHub

https://ithelp.ithome.com.tw/upload/images/20210920/20111805AMd8uNsYxL.png

今天的目标

就用文章列表作为范例,如果是使用我的范例档案记得帮我下下面两个指令来迁移资料库及新增假资料到资料库中!

php artisan migrate

php artisan db:seed

提醒:记得修改自己的 .env 档中的资料库名称、与使用者帐号密码。

首先先刻一个表格画面

<table class="ui celled table">
    <thead>
        <tr>
            <th>Num.</th>
            <th>Author</th>
            <th>Title</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-label="Num.">123</td>
            <td data-label="Author">王小明</td>
            <td data-label="Title">关於中秋吃月饼及烤肉这档事</td>
        </tr>
    </tbody>
</table>

设定後端

在最上面要引入两个东西,分别是 分页的套件Post的Model

use Livewire\WithPagination;

use App\Models\Post;

并在 Class 内使用该套件:

class Day18 extends Component
{
    use WithPagination;
    ...

接着在 render() 中顺便渲染文章列表,并使用分页功能,这边设定为每页10笔资料paginate(10)

public function render()
{
    return view('livewire.example.day18', [
        'posts' => Post::paginate(10),
    ]);
}

完整看起来会是这样:

<?php

namespace App\Http\Livewire\Example;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Post;

class Day18 extends Component
{
    use WithPagination;

    public function render()
    {
        return view('livewire.example.day18', [
            'posts' => Post::paginate(10),
        ]);
    }
}

前端补上 Livewire 的内容

把静态资料移除,并用 @foreach 套上资料库中拿来的文章资料。

在底下加上 {{ $posts->links() }} 就可以自动生成分页的选择器!

<table class="ui celled table">
    <thead>
        <tr>
            <th>Num.</th>
            <th>Author</th>
            <th>Title</th>
        </tr>
    </thead>
    <tbody>
        @foreach($posts as $post)
        <tr>
            <td data-label="Num.">{{ $post->id }}</td>
            <td data-label="Author">{{ $post->author }}</td>
            <td data-label="Title">{{ $post->title }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
<br>
<div>
    {{ $posts->links() }}
</div>

完成

到这里就完成了文章列表还能切换分页的功能啦!!

此外 Livewire 也有内建 bootstrap 的主题,可以使用 $paginationTheme 来指定样式,之後 $posts->links() 将会生成符合 bootstrap 分页样式的 HTML,如下图:

https://ithelp.ithome.com.tw/upload/images/20210920/20111805aMiv5tok8j.png

class Day18 extends Component
{
    use WithPagination;
    
    protected $paginationTheme = 'bootstrap';

如果想要自订样式也是完全可以做到的,不过比较复杂也不常用,就详见 官方文件


<<:  .Net Core Web Api_笔记12_自定义属性路由

>>:  Day-05 Ruby 的世界里,万物都是物件?

以Postgresql为主,再聊聊资料库 typed table的应用

上一篇介绍了 create type,以及 typed table. 本篇介绍应用,这次就不做复合型...

关於计算机,你必须知道的事: CPU 快取

本文目标 记忆体层接 介绍快取的组成 常见的快取机制 使用快取需要面对的同步问题 进入正题 CPU ...

比尔盖兹的养鸡理论与台湾鸡农养鸡经验谈

比尔.盖兹旗下的基金会曾经对贫穷国家献计改善,他的策略就是「养鸡」来脱贫,但有人觉得比尔.盖兹是不是...

【Day 20】Algorithm - Practice 2

接下来是一题迄今为止,作业中最复杂的一题,虽然不会太难,但是要把逻辑整理清楚,而且给予自己足够的信心...

[Day14] 团队系统设计 - 重塑 Planning 会议

本篇文章来介绍「规画系统」(Planning System) 中的:Planning 会议。我相信熟...