如何从数组向Blade组件传参?组件未渲染问题求解
问题原因
Blade模板采用先编译后执行的机制,你在<x-buttons-button>标签内部用@foreach动态拼接属性的写法,会被Blade当成普通文本处理,不会触发组件的编译逻辑,因此最终输出的是未解析的原始组件标签。
解决方案
推荐使用Blade官方的@component指令来动态传递数组属性,这是最符合Blade规范的写法:
修改<x-buttons-group>组件的循环部分代码:
<div class="{!!$fullWidth!!} flex flex-row space-x-0 overflow-hidden rounded-lg border {!!$borderColor!!}"> <ul class="flex w-full flex-row space-x-0"> @foreach($buttons as $button) <li class="children:border-0 children:rounded-none w-full border-r {!!$borderRightColor!!} last:border-r-0"> @component('components.buttons-button', $button) @endcomponent </li> @endforeach </ul> </div>
@component的第一个参数是组件的完整路径(如果你的组件在resources/views/components/buttons/button.blade.php,路径就是components.buttons-button,和<x-buttons-button>的命名对应)- 第二个参数直接传入
$button数组,数组的键会自动映射为组件的属性名,值对应属性值,无需手动循环拼接
如果偏好自闭合标签的写法,也可以用Blade::render动态渲染组件:
<div class="{!!$fullWidth!!} flex flex-row space-x-0 overflow-hidden rounded-lg border {!!$borderColor!!}"> <ul class="flex w-full flex-row space-x-0"> @foreach($buttons as $button) <li class="children:border-0 children:rounded-none w-full border-r {!!$borderRightColor!!} last:border-r-0"> {!! Blade::render('<x-buttons-button :type="$type" :content="$content" :leadingIcon="$leadingIcon" :trailingIcon="$trailingIcon" />', $button) !!} </li> @endforeach </ul> </div>
这种方式需要手动列出所有属性,灵活性不如@component,仅作为备选方案。
内容的提问来源于stack exchange,提问作者Andrei RRR
相关产品推荐
相关产品推荐

