【发布时间】:2022-11-11 01:34:12
【问题描述】:
我想使用一个数组并用它来动态填充 laravel-blade (8.x) 组件的道具。简而言之,就是这样:
<x-button size="sm" {{ $buttonProps }} /> 其中$buttonProps 是一个包含键值对的数组,用于定义要呈现的按钮的道具及其值。
数组看起来像这样:['label' => 'My Button', 'size' => 'sm', ...]
这是我尝试做的更详细的示例:
1. 带有一些道具的按钮组件
@props([
'size' => 'md', # sm, md, lg
'variant' => 'basic', # basic, success, error
'label' => '',
])
@php
// ...
@endphp
<button {{ $attributes->merge([ 'class' => '...' ]) }}>
{!! $label !!}
</button>
2. ButtonGroup - 它将使用数组作为道具呈现按钮
这是不起作用的东西:{{ $buttonProps }}。我想将 Button 的道具作为数组动态传递。但是这个解决方案当然不是那样工作的。有解决方案吗?
@props([
'buttons' => []
])
<div class="...">
@foreach ($buttons as $buttonProps)
<x-button size="sm" {{ $buttonProps }} />
@endforeach
</div>
3. 最后我将如何在这种情况下使用 ButtonGroup
你可能会注意到我给第一个按钮传递了一些额外的道具。这基本上就是为什么我需要一种动态方法,因为我不知道在我的现实生活场景中传递的所有道具。
<x-button-group
:buttons="[
[
'label' => 'Export',
'hello' => 'world',
'type' => 'button',
'onclick' => '() => alert(\'hello world\')',
],
[
'label' => 'Main action',
'variant' => 'accent',
]
]"
/>
注意:我知道我可以在这里使用插槽轻松地使这个示例运行,但是我的实际示例在要求上略有不同。我以 Button 和 ButtonGroup 为例来说明我的问题。
【问题讨论】: