Laravel Livewire 分页问题

打印 上一主题 下一主题

主题 576|帖子 576|积分 1728

场景:

博客的文章列表需要增长分页,代码及报错信息如下:
  1. <?php
  2. namespace App\Livewire\Components;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Livewire\Component;
  5. use App\Models\Article as ArticleModel;
  6. use Livewire\WithPagination;
  7. class Article extends Component
  8. {
  9.     use WithPagination;
  10.     public $articles;
  11.     public function mount($category_id = false)
  12.     {
  13.         $this->articles = ArticleModel::query()
  14.             ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
  15.             ->with('category')
  16.             ->when($category_id, function (Builder $query, string $category_id) {
  17.                 $query->where('category_id', $category_id);
  18.             })
  19.             ->orderByDesc('id')
  20.             ->paginate(10);
  21.     }
  22.     public function render()
  23.     {
  24.         return view('livewire.components.article', [
  25.             'articles' => $this->articles,
  26.         ]);
  27.     }
  28. }
复制代码
Property type not supported in Livewire for property:

缘故原由是 livewire 组件类中属性不支持分页对象,以是导致报错
解决方法:

将原有的查询逻辑代码由 mount 转移到 render 方法中。
  1. <?php
  2. namespace App\Livewire\Components;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Livewire\Component;
  5. use App\Models\Article as ArticleModel;
  6. use Livewire\WithPagination;
  7. class Article extends Component
  8. {
  9.     use WithPagination;
  10.     public $category_id;
  11.     public function mount($category_id = false)
  12.     {
  13.         $this->category_id = $category_id;
  14.     }
  15.     public function render()
  16.     {
  17.         $category_id = $this->category_id;
  18.         $articles = ArticleModel::query()
  19.             ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
  20.             ->with('category')
  21.             ->when($category_id, function (Builder $query, string $category_id) {
  22.                 $query->where('category_id', $category_id);
  23.             })
  24.             ->orderByDesc('id')
  25.             ->paginate(10);
  26.         return view('livewire.components.article', [
  27.             'articles' => $articles,
  28.         ]);
  29.     }
  30. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

道家人

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表