PCS開発チーム
PCS開発チーム
Livewire Voltでレイアウトにデータを渡す方法
LivewireとVoltのコードを調べまくってやっと分かった。
バージョン
- Laravel11
- Livewire 3.4
- Volt 1.6
今の方法は分かりやすくないので将来のバージョンでは変わってる可能性が高い。
functional Voltの場合
rendering()
とかlayoutData()
とか分かりやすい機能が用意されてないのでmount()
かboot()
かbooted()
でComponentのAttributeCollectionに直接追加する強引な方法しかなかった。
// functional Volt
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
use function Livewire\Volt\mount;
mount(function () {
/** @var Component $this */
$this->attributes->add(new Layout('layouts.app', ['foo' => 'test']));
});
// layout blade
{{ $foo ?? '' }}
コンポーネント内のプロパティも渡せる。
// functional Volt
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
use function Livewire\Volt\mount;
use function Livewire\Volt\state;
state(['foo' => 'test']);
mount(function () {
/** @var Component $this */
$this->attributes->add(new Layout('layouts.app', ['foo' => $this->foo]));
});
ルートパラメーターも渡せる。
// routes/web.php
use Livewire\Volt\Volt;
Volt::route('user/{user}', 'pages.user');
// functional Volt
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
use function Livewire\Volt\mount;
mount(function (User $user) {
/** @var Component $this */
$this->attributes->add(new Layout('layouts.app', ['user' => $user]));
});
// layout blade
{{ $user->name ?? '' }}
mount()
かboot()
かbooted()
かはLivewireのLifecycle hooksの違いでしかないので最初にデータを渡すだけならどれでも結果は同じ。
Class-based Voltなら簡単
普通のLivewireの使い方とほとんど同じ。
// Class-based Volt
use Illuminate\View\View;
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
new #[Layout('layouts.app')] class extends Component {
//
public function rendering(View $view): void
{
$view->title('...');
$view->layoutData(['foo' => 'test']);
}