【问题标题】:Laravel 8 Livewire component Undefined variable: headerLaravel 8 Livewire 组件未定义变量:标头
【发布时间】:2021-03-26 20:17:50
【问题描述】:

我在 Jetstream 中创建了一个 Livewire 组件,并在web.php 路由页面中将其设置为整页组件,如下所示:

use App\Http\Livewire\PostComponent;
...
Route::get('posts/',PostComponent::class)->name('posts');

post-component.blade.php文件原来有以下代码:

<div>
    <h1>If you look to others for fulfillment, you will never truly be fulfilled.</h1>
</div>

如果我点击 URL .../posts 我会收到以下错误:

未定义变量:标头(查看: /home/vagrant/laravelapp/resources/views/layouts/app.blade.php)

所以我尝试在post-component.blade.php 文件中添加插槽:

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>
    <div>
        <h1>If you look to others for fulfillment, you will never truly be fulfilled.</h1>
    </div>
</x-app-layout>

不过,我得到了同样的错误。

我错过了什么?我该如何解决这个问题?

【问题讨论】:

  • 检查插槽header是否存在于组件x-app-layout
  • 谢谢。我正在检查 M Irfan 提供的 GitHub issue 链接。

标签: laravel laravel-livewire


【解决方案1】:

我希望这是一个Jetstream 项目。默认情况下,livewire 将使用app.blade.php 作为布局。并且组件将在app.blade.phpslot 中呈现。

但由于它是一个 Jetstream 项目,所以它在布局文件中为 header 提供了一个插槽。

  <header class="bg-white shadow">
       <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
             {{ $header }}
        </div>
  </header>

所以要解决这个错误,有两种方法。

  1. PostComponent.php 中将标题作为布局的变量,如下所示

 public function render()
 {
        return view('livewire.post-component')
         ->layout('layouts.app', ['header' => 'Post Compoent Page']);
 }
  1. 创建您自己的布局并且只有一个插槽。 (想象一下mylayout.blade.php

<head>
    @livewireStyles
</head>
<body>
    {{ $slot }}

    @livewireScripts
</body>

并在渲染 livewire 组件时使用该布局

public function render()
{
   return view('livewire.post-component')->layout('layouts.mylayout');
}

关于这个话题有一个githubissue(一个封闭的)。但请留意它。因为Jetstream 还处于早期阶段。

【讨论】:

  • 我忘了强调我正在使用Jetstream。你猜对了。确实。也感谢 Github 问题链接。
猜你喜欢
  • 2021-04-19
  • 2021-09-18
  • 2023-01-14
  • 1970-01-01
  • 2021-01-10
  • 2021-10-31
  • 1970-01-01
  • 2022-11-11
  • 2022-06-11
相关资源
最近更新 更多