Livewire插槽无法渲染,变量未定义问题求助
问题
我尝试创建一个表格并让操作列具备灵活性,打算通过插槽实现操作列的动态变更,预期用法如下:
<livewire:tables.products.overview> <x-slot:slotName> Some data here </x-slot:slotName> </livewire:tables.products.overview>
但在overview组件模板中编写如下代码渲染命名插槽时:
<div> Render the slot here: -> {{$slotName}} <- </div>
出现错误:Undefined variable $slotName。
我尝试改用默认插槽,将overview.blade.php修改为:
<div> Render the slot here: -> {{$slot}} <- </div>
并按如下方式调用:
<livewire:tables.products.overview> <div> My slot will be placed here </div> </livewire:tables.products.overview>
仍报错:Undefined variable $slot。请问我遗漏了什么关键配置或步骤?
解决方法
Livewire组件的插槽机制和原生Blade组件不同,不能直接在模板中调用$slot或命名插槽变量,需按以下步骤调整:
在组件类中声明插槽属性
打开Overview.php组件类,为插槽添加对应的属性,命名插槽要使用#[Slot]注解标记(适用于Livewire 3.x):use Livewire\Component; use Livewire\Attributes\Slot; class Overview extends Component { // 声明默认插槽属性 public $slot; // 声明命名插槽并添加注解 #[Slot] public $slotName; public function render() { return view('livewire.tables.products.overview'); } }在模板中正确渲染插槽
模板里直接使用声明好的属性名渲染对应的插槽内容:<div> <!-- 渲染默认插槽 --> 默认插槽内容:{{ $slot }} <!-- 渲染命名插槽 --> 操作列内容:{{ $slotName }} </div>适配Livewire 2.x版本(若使用旧版)
如果你用的是Livewire 2.x,命名插槽需要用@slot语法调用:<livewire:tables.products.overview> @slot('slotName') <button>编辑</button> <button>删除</button> @endslot </livewire:tables.products.overview>模板中通过
$slots->get()方法获取插槽内容:<div> {{ $slots->get('slotName') }} </div>
内容的提问来源于stack exchange,提问作者Donny van V
相关产品推荐
相关产品推荐

