场景:
博客的文章列表需要增长分页,代码及报错信息如下:
- <?php
- namespace App\Livewire\Components;
- use Illuminate\Database\Eloquent\Builder;
- use Livewire\Component;
- use App\Models\Article as ArticleModel;
- use Livewire\WithPagination;
- class Article extends Component
- {
- use WithPagination;
- public $articles;
- public function mount($category_id = false)
- {
- $this->articles = ArticleModel::query()
- ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
- ->with('category')
- ->when($category_id, function (Builder $query, string $category_id) {
- $query->where('category_id', $category_id);
- })
- ->orderByDesc('id')
- ->paginate(10);
- }
- public function render()
- {
- return view('livewire.components.article', [
- 'articles' => $this->articles,
- ]);
- }
- }
复制代码 Property type not supported in Livewire for property:
缘故原由是 livewire 组件类中属性不支持分页对象,以是导致报错
解决方法:
将原有的查询逻辑代码由 mount 转移到 render 方法中。
- <?php
- namespace App\Livewire\Components;
- use Illuminate\Database\Eloquent\Builder;
- use Livewire\Component;
- use App\Models\Article as ArticleModel;
- use Livewire\WithPagination;
- class Article extends Component
- {
- use WithPagination;
- public $category_id;
- public function mount($category_id = false)
- {
- $this->category_id = $category_id;
- }
- public function render()
- {
- $category_id = $this->category_id;
- $articles = ArticleModel::query()
- ->select(['id', 'category_id', 'title', 'description', 'reading_quantity', 'comment_quantity'])
- ->with('category')
- ->when($category_id, function (Builder $query, string $category_id) {
- $query->where('category_id', $category_id);
- })
- ->orderByDesc('id')
- ->paginate(10);
- return view('livewire.components.article', [
- 'articles' => $articles,
- ]);
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |