你好!
经过一个小时的尝试解决问题后,我决定提出一个新问题。我遇到了一个很常见的问题,但没有 101 个修复对我有用。
我的“体验”视图组件刀片无法访问其“体验”类公共变量。它甚至不调用它的 __construct 方法。
Experiences.php (应用程序/视图/组件/所有者/卡片内容)
<?php
namespace App\View\Components\Owners\CardContents;
use App\Models\Owner;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Experiences extends Component
{
public HasMany $ownerExperiences;
/**
* Create a new component instance.
* Get the 6 topmost experiences, with the highest prefference number and then ordered by date.
*/
public function __construct(Owner $owner)
{
$this->ownerExperiences =
$owner->ownerExperiences()->orderByDesc('prefferenceNumber')->orderByDesc('date')->limit(6)->orderBy('date');
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.owners.card-contents.experiences');
}
}
experiences.blade.php (资源/视图/组件/所有者/卡片内容)
<section class="timeline pb-3" id="timeline">
<div class="timeline-body">
@foreach($ownerExperiences as $ownerExperience)
@endforeach
当尝试运行 foreach 时,laravel 说:未定义的变量 $ownerExperiences
我想要组件做什么:
访问视图内的公共 $ownerExperiences 变量(存储在组件类中)
我尝试过但没有解决问题:
运行“作曲家转储”
运行'php artisan view:clear'
删除组件并使用相同的内容再次创建它们 'php artisan make:component Owners/CardContents/Experiences'
重命名组件,然后将它们重命名回来
将 'dd()' 放入类 __construct 方法中 - 仍然出现相同的错误
我认为问题可能是:
老实说,我可能发现的唯一一件事是我使用的是 @component 指令,而不是使用其
@component("components.owners.card-contents.$key", ['owner' => $owner, 'index' => $index])
@endcomponent
好的!
正如 @apokryfos 在评论中所述, @component 指令直接渲染视图,绕过组件类。通过使用dynamic-component,问题已经解决了!
我改变了这个:
@component("components.owners.card-contents.$key", ['owner' => $owner, 'index' => $index])
@endcomponent
对此:
@php
$componentName = "owners.card-contents.$key";
@endphp
<x-dynamic-component :$owner :index="$index" :component="$componentName" />
它就像一个魅力! 但仍有一个问题需要解决:
我无法直接访问动态组件传入的变量!
这不起作用:
array_unshift($descriptions, \Carbon\Carbon::parse($owner->user->born)->age . " Let");
但我可以这样访问它:
$owner = $attributes['owner'];
有谁知道这是否是最佳实践或如何修复对传入变量的直接访问?