續上一篇使用 card 的 component,接著如果我們想要對 component 的元素設定 attribute,可以使用 $attribute 像這樣:

<div {{ $attributes }}>test</div>

 

接著在使用 component 的時候設定 class name 就可以了:

<x-card title="標題" class="text-danger">
  <x-slot name="footer">this is footer</x-slot>
  hello component
</x-card>

 

那如果有時要結合預設的 class name,又有想把變數的帶進去的需求,可以用 merge 來結合預設的 class name:

<div {{ $attributes->merge(['class' => 'text-'.$type]) }}>test</div>

 

在帶進 component 則是這樣:

<x-card title="標題" type="danger" class="py-2">
  <x-slot name="footer">this is footer</x-slot>
  hello component
</x-card>

這樣那個區塊就會變成以下的樣子:

<div class="text-danger py-2">

 

以下是在不同條件使用不同 class 的方法:

<div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>
    {{ $message }}
</div>

 

要結合不同 attribute 的方法:

<button {{ $attributes->class(['p-4'])->merge(['type' => 'button']) }}>
    {{ $slot }}
</button>

 

不設定 class name:

<button {{ $attributes->merge(['type' => 'button']) }}>
    {{ $slot }}
</button>

使用 component 的地方:

<x-button type="submit">
    Submit
</x-button>

 

使用 filter 過濾內容:

{{ $attributes->filter(fn ($value, $key) => $key == 'foo') }}

 

設定以某(不以)個字串開始:

{{ $attributes->whereStartsWith('wire:model') }}
{{ $attributes->whereDoesntStartWith('wire:model') }}

 

基於以上條件的第一筆:

{{ $attributes->whereStartsWith('wire:model')->first() }}

 

判斷是否有某個 class:

@if ($attributes->has('class'))
    <div>Class attribute is present</div>
@endif

 

取得 class name:

{{ $attributes->get('class') }}

 

參考:Laravel Component