assertchris / laravel-renderless-components
使用延迟评估的内容创建组件
1.1.0
2020-07-21 07:18 UTC
Requires
- php: ^7.4
README
Blade组件很棒,不是吗?它们中我还缺少的是创建无渲染组件的方法。Blade从上到下渲染,这意味着您无法延迟评估子内容。想象一下,您能够这样定义和使用组件
<ul class="space-y-2"> @foreach ($items as $item) <li class="text-gray-900">{{ $render($item, $loop->count) }}</li> @endforeach </ul>
<x-list :items="$items"> {{ $item }} (of {{ $count }}) </x-list>
因此,我找到了一种方法来实现它。您需要定义您的PHP组件如下
namespace App\View\Components; use RenderlessComponents\RenderlessComponent; class List extends RenderlessComponent { public array $items = []; public function __construct(array $items) { $this->items = $items; } public function view(): string { return 'components.tailwind-list'; } public function viewParams(): array { // think of this as the array of params // you usually give as the second argument // of the view() function return [ 'items' => $this->items, ]; } public function renderParams(): string { // think of this as the list of arguments // you give to the render function return '$params, $count'; } }
用法
将库添加到您的项目中
composer require assertchris/laravel-renderless-components
它会自动注册,所以您只需要扩展RenderlessComponents\RenderlessComponent
而不是Illuminate\View\Component
并实现抽象方法。
注意事项
- 我已经更改了延迟评估内容的缓存方式,以便这个库可以与
facade/ignition
一起工作。在本地(或在任何其他环境,如果该文件已存在);延迟评估的内容被缓存在storage/framework/views/components
文件夹中。如果您的视图没有更新,那么您可能不在local
环境中。您可以更改环境或删除该文件夹中的缓存文件。