Laravel-Livewire笔记系列(七)-Livewire 事件机制新数据与分页-3

作者: 温新

分类: 【Laravel】

阅读: 1745

时间: 2021-11-16 13:10:04

作者:温新

时间:2021-08-14

hi,我是温新,一名PHPer

1)本系列笔记使用Laravel8.x作为演示;

2)使用Livewire2.x版本

在 发布留言 的过程中存在一个问题,那就是留言发布后,列表数据并没有显示出来。这个问题该如何解决?可以使用Livewire中的触发事件来解决。

数据更新

第一步:留言发布后发出事件

App\Http\Livewire\LeaveMsgCreate.php

// 发布留言
public function createLeaveMsg()
{
	// 省略添加留言代码
    
    // 发送事件
    $this->emit('refreshMsg');
}

第二步:监听事件

App\Http\Livewire\LeaveMsgIndex.php

use App\Models\LeaveMsg;

// 监听事件
protected $listeners = ['refreshMsg'];

// 就是这样什么都不要写
public function refreshMsg()
{
}

ajax数据分页

传统的分页会使得页面重新加载。Livewire提供了一个更加友好的ajax无感刷新分页。

第一步:使用分页

// app/Http/Livewire/LeaveMsgIndex.php
use Livewire\WithPagination;

class LeaveMsgIndex extends Component {
	use WithPagination;

    public function render()
    {
        $leaveMsgs = LeaveMsg::paginate(5);

        return view('livewire.leave-msg-index', compact('leaveMsgs'));
    }    
}

第二步:视图分页

// resources/views/livewire/leave-msg-index.blade.php
<div>
    <livewire:leave-msg-create />

    <ul>
        @foreach($leaveMsgs as $v)
            <li>{{$v->user->name}}--{{ $v->content }}</li>
        @endforeach
    </ul>

    {{ $leaveMsgs->links() }}
</div>

到这里,留言发布即使显示就完成啦。

我是温新

每天进步一点点,就一点

请登录后再评论