ToB企服应用市场:ToB评测及商务社交产业平台

标题: Laravel Livewire 分页问题 [打印本页]

作者: 道家人    时间: 2024-6-21 18:04
标题: Laravel Livewire 分页问题
场景:

博客的文章列表需要增长分页,代码及报错信息如下:
  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企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4