[英]use paginate in livewire components
我有一個看起來像的組件
<?php
namespace App\Http\Livewire\Comments;
use App\Models\Comment;
use Livewire\Component;
use Livewire\WithPagination;
class ShowComments extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $comments;
public function getListeners()
{
return ['commentAdded'];
}
public function mount(){
$this->comments = Comment::latest()->get();
}
public function commentAdded(){
$this->comments = Comment::latest()->paginate(5);
}
public function render()
{
return view('livewire.comments.show-comments');
}
}
當我嘗試使用paginate
時出現以下錯誤。
Livewire component's [comments.show-comments] public property [comments] must be of type: [numeric, string, array, null, or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't need to access them.
當在帖子上添加評論時,我從SinglePost
組件觸發一個事件以重新呈現ShowComments
組件。
//emit the event to ShowComments component
$this->emit('commentAdded');
我在我的ShowPosts
組件的渲染方法中使用分頁方法,例如
public function render()
{
return view('livewire.posts.show-posts', [
'posts' => Post::latest()->paginate(5)
]);
}
但是這樣做不允許我監聽事件並刷新/重新渲染組件。 有什么解決方法可以讓我對公共屬性使用分頁嗎?
通過查看您的代碼,我在 ShowComments 組件中發現了一些功能錯誤。
首先$comments
裝載了從 get() 方法檢索的結果,因此最初$comments
持有 Collection Object 數據類型。 稍后當您使用$this->comments = Comment::latest()->paginate(5);
在事件監聽器中更新它時 , $comments
被修改為持有 Paginate Object 數據類型。
這就是Livewire component's [comments.show-comments] public property [comments] must be of type: [numeric, string, array, null, or boolean].
如果你想為評論組件使用分頁,那么你必須在 render 方法本身中聲明它。 稍后,當您需要使用事件偵聽器刷新評論時,您可以簡單地調用$this->refresh()
。 這將重新獲取評論並基本上刷新評論組件。
在上述更新之后,您ShowComments
組件應該看起來像這樣:
<?php
namespace App\Http\Livewire\Comments;
use App\Models\Comment;
use Livewire\Component;
use Livewire\WithPagination;
class ShowComments extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public function getListeners()
{
return ['commentAdded'];
}
public function commentAdded(){
//refreshes ShowComments component
$this->refresh();
}
public function render()
{
return view('livewire.comments.show-comments',[
'comments' => Comment::latest()->paginate(5)
]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.