Livewire 公共属性类型限制及分页解决方案

livewire 公共属性类型限制及分页解决方案

在 Livewire 组件开发中,我们可能会遇到如下错误:Livewire/Exceptions/PublicPropertyTypeNotAllowedException Livewire component’s [your-component] public property [yourProperty] 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. 这表明你试图将一个不允许的类型(例如 Eloquent 模型集合、Paginator 实例等)赋值给一个公共属性。Livewire 这样做是为了确保前端 JavaScript 只能访问安全的数据类型,防止潜在的安全风险。

当需要分页显示数据时,直接将 Illuminate/Pagination/LengthAwarePaginator 实例赋值给公共属性 samples 会触发此异常。这是因为 paginate() 方法返回的是一个 LengthAwarePaginator 实例,而 Livewire 不允许将其直接作为公共属性。

解决方案:

一种有效的解决方案是将数据传递到视图中,而不是在 mount 方法中直接设置公共属性。以下步骤详细说明了如何实现:

  1. 移除 mount 方法中的分页逻辑:

    首先,移除 mount 方法中设置 $this->samples 的代码。不再直接在组件的 mount 方法中进行分页查询,避免将 LengthAwarePaginator 实例赋值给公共属性。

  2. 在 render 方法中进行分页查询:

    在 render 方法中执行分页查询,并将结果通过 compact 函数传递给视图。

    public function render()
    {
        $samples = Sample::whereLabId($this->lab->id)->paginate(5);
    
        return view('livewire.your-component', compact('samples'));
    }
    登录后复制
  3. 在 Livewire 视图中使用分页链接:

    在 Livewire 视图 resources/views/livewire/your-component.blade.php 中,使用 Laravel 的分页链接来显示分页导航:

    <div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <!-- 其他列 -->
                </tr>
            </thead>
            <tbody>
                @foreach($samples as $sample)
                    <tr>
                        <td>{{ $sample->id }}</td>
                        <!-- 其他列 -->
                    </tr>
                @endforeach
            </tbody>
        </table>
    
        {{ $samples->links() }}
    </div>
    登录后复制

示例代码:

以下是一个完整的示例,展示了如何在 Livewire 组件中使用分页功能:

<?php

namespace App/Http/Livewire;

use Livewire/Component;
use App/Models/Sample;
use App/Models/Lab;
use Livewire/WithPagination;

class SampleData extends Component
{
    use WithPagination;

    public $lab;
    public $sample;

    public function mount($lab = null)
    {
        $this->sample = new Sample;

        if ($lab) {
            $this->lab = Lab::find($lab);
        }
    }

    public function render()
    {
        $samples = Sample::whereLabId($this->lab->id)->paginate(5);

        return view('livewire.sample-data', compact('samples'));
    }
}
登录后复制

注意事项:

  • 确保在 Livewire 组件中使用 WithPagination trait,以便正确处理分页链接。
  • 视图中使用的变量名必须与 compact 函数中传递的变量名一致。
  • 如果需要在分页链接中传递其他参数,可以使用 appends 方法。
  • tailwind需要引入分页样式,否则分页样式会错乱。

总结:

通过将分页逻辑放在 render 方法中,并将分页数据通过 compact 函数传递给视图,我们可以有效地绕过 Livewire 的公共属性类型限制,并实现分页功能。这种方法既保证了数据的安全性,又充分利用了 Livewire 的响应式特性。

以上就是Livewire 公共属性类型限制及分页解决方案的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1443464.html

发表回复

Your email address will not be published. Required fields are marked *