使用分页数据时 Livewire 抛出错误
Posted
技术标签:
【中文标题】使用分页数据时 Livewire 抛出错误【英文标题】:Livewire throwing error when using paginated data 【发布时间】:2021-02-19 14:08:31 【问题描述】:因此,当我尝试对我的数据进行分页并通过 livewire 组件将其发送到视图时出现此错误。
我正在尝试使用 laravel 中的分页获取所有帖子并以每页最多 5 个帖子显示。
Livewire 版本:2.3.1 Laravel 版本:8.13.0
错误:
Livewire\Exceptions\PublicPropertyTypeNotAllowedException
Livewire component's [user-posts] public property [posts] 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.
我的组件:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
use Livewire\WithPagination;
class UserPosts extends Component
use WithPagination;
public $posts;
public $type;
protected $listeners = ['refreshPosts'];
public function delete($postId)
$post = Post::find($postId);
$post->delete();
$this->posts = $this->posts->except($postId);
public function render()
if($this->type == 'all')
$this->posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$this->posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $this->posts]);
我的刀锋:
<div wire:poll.5s>
@foreach($posts as $post)
<div style="margin-top: 10px">
<div class="post">
<div class="flex justify-between my-2">
<div class="flex">
<h1> $post->title </h1>
<p class="mx-3 py-1 text-xs text-gray-500 font-semibold"
style="margin: 17px 0 16px 40px"> $post->created_at->diffForHumans() </p>
</div>
@if(Auth::id() == $post->user_id)
<i class="fas fa-times text-red-200 hover:text-red-600 cursor-pointer"
wire:click="delete($post->id)"></i>
@endif
</div>
<img src=" asset('image/banner.jpg') " style="height:200px;"/>
<p class="text-gray-800"> $post->text </p>
@livewire('user-comments', [
'post_id' => $post->id,
'type' => 'all'
],
key($post->id)
)
</div>
</div>
@endforeach
$posts->links()
</div>
【问题讨论】:
【参考方案1】:$posts 不应在 Livewire 组件类中声明为属性,您将带有 laravel view() 助手的帖子作为数据传递。
删除线
public $posts;
并在渲染函数中将 $this->posts 替换为 $posts:
public function render()
if($this->type == 'all')
$posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $posts]);
【讨论】:
这是答案,非常感谢朋友 这也适用于我。但我不明白为什么会这样。为什么公共财产会导致这个问题? 非常感谢!!!拯救了我的一天:)以上是关于使用分页数据时 Livewire 抛出错误的主要内容,如果未能解决你的问题,请参考以下文章
Laravel Livewire 无法解析模板上分页的雄辩关系
点击gotoPage方法后如何在livewire中调用JS函数?
使用 Jetstream 在 Laravel 8 中添加新 Livewire 组件时如何解决 RootTagMissingFromViewException 错误