在动态组件中使用分页



我有一个组件看起来像

<?php
namespace AppHttpLivewireComments;
use AppModelsComment;
use LivewireComponent;
use LivewireWithPagination;
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组件的渲染方法中使用paginate方法,如

public function render()
{
return view('livewire.posts.show-posts', [
'posts' => Post::latest()->paginate(5)
]);
}

,但这样做不允许我监听事件和刷新/重新呈现组件。有什么方法可以解决这个问题,这样我就可以使用公共属性分页了吗?

通过查看您的代码,我发现了ShowComments组件中的一些功能错误。

首先,$comments是用get()方法获取的结果挂载的,所以最初$comments持有集合对象数据类型。稍后,当您使用$this->comments = Comment::latest()->paginate(5);在事件侦听器中更新它时,$comments被修改为保存分页对象数据类型。

这是错误的原因Livewire component's [comments.show-comments] public property [comments] must be of type: [numeric, string, array, null, or boolean].

如果你想使用Pagination for comments组件,那么你必须在render方法中声明它。稍后,当需要使用事件侦听器刷新注释时,只需调用$this->refresh()即可。它将重新获取注释并刷新注释组件。

你的ShowComments组件应该看起来像上面的更新:

<?php
namespace AppHttpLivewireComments;
use AppModelsComment;
use LivewireComponent;
use LivewireWithPagination;
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)
]);
}
}

最新更新