我正在 Laravel 8 中在某些地方使用 x-components 构建网页。组件是存在于所有页面中的模式,但其内容必须根据调用它的页面而改变。
我的想法如下:
- IndexController 使用 PageModel 将 $pageid 传递给 index.blade View
- index.blade 将 $pageid 传递给 x-insert-section 组件
- x-insert-section 组件在@switch 指令中使用它来显示每页所需的内容
问题在于 x-insert-section 似乎在 $pageid 中没有收到任何值。
代码如下:
我的 IndexController.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Page;
use App\Models\Entry;
use Illuminate\Http\Request;
class IndexController extends Controller
{
public function init(Request $request)
{
$page = Page::where('slug', '/')->first();
return view('index', [
'page' => $page,
'entries' => Entry::where('page', $page->id)->get(),
'pageid' => $page->id
]);
}
}
index.blade.php 中加载 x 组件的部分
<x-insert-section :pageid="$pageid"></x-insert-section>
<x-insert-jumbo-image :pageid="$pageid"></x-insert-jumbo-image>
InsertSection.php 组件
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class InsertSection extends Component
{
public function __construct(){}
public $pageid;
public function render()
{
return view('components.insert-section');
}
}
insert-section.blade.php 的 View (开关内容已替换为注释以减少代码长度)
<div class="modal fade" id="create-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-entry-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
@switch($pageid)
@case('1')
<!-- Form type 1 -->
@break
@case('3')
<!-- Form type 2 -->
@break
@default
Default Case
@endswitch
</div>
<div class="modal-footer">
<button id="confirm-entry" type="submit" form="create-form" class="btn btn-primary">{{$pageid}}</button>
</div>
</div>
</div>
</div>
注意:我尝试使用 '1' 和 1 作为 switch case 的值,即使发送硬编码字符串,也没有任何效果
最后,调用模态框时屏幕上的结果。未加载任何表单,开关解析为默认大小写。
任何帮助将不胜感激。
最佳答案
事实证明我在阅读文档后找到了解决方案(祝福他们,该死的我的阅读差)
缺少的部分是接收变量的构造函数,因此代码以这种方式更改。
InsertSection.php 组件
发件人:
public function __construct(){}
public $pageid;
收件人:
public $pageid;
public function __construct($pageid)
{
$this->pageid = $pageid;
}
我知道我知道,这很有意义,但我想我下次会记住的。
关于php - 无法将变量传递给 Laravel x 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65774098/