代码之家  ›  专栏  ›  技术社区  ›  Moshe

Laravel刀片组件中灵活的HTML标记

  •  0
  • Moshe  · 技术社区  · 3 年前

    我创建了一个刀片组件,有时需要将其渲染为标记,有时需要渲染为按钮。为了实现这一点,我创建了以下组件:

    @props([
      'number',
      'tag' => 'a'
    ])
    
    @php
      $classes = 'text-gray-700 hover:text-gray-900 hover:bg-gray-100 block px-4 py-2 text-sm';
    @endphp
    
    @if ($tag === 'a')
      <a
        tabindex="-1"
        role="menuitem"
        id="menu-item-{{ $number }}"
        class="{{ $classes }}"
        {{ $attributes }}
      >
        {{ $slot }}
      </a>
    
    @else
      <button
        type="submit"
        tabindex="-1"
        role="menuitem"
        id="menu-item-{{ $number }}"
        class="{{ $classes }} w-full text-left"
      >
        {{ $slot }}
      </button>
    @endif
    

    现在,这是可行的,但它不是很干燥。因此,我想知道是否有一种更干爽、更优雅的方式让我达到同样的效果。

    有什么想法吗?

    1 回复  |  直到 3 年前
        1
  •  0
  •   medilies    3 年前

    首先注意这种可能性

    @php
        $tag = 'a';
    @endphp
    <{{ $tag }}>yo</{{ $tag }}>
    

    但我更喜欢使用较小的组件(微组件?)这将帮助您重构共享属性。

    @php
        $classes = 'text-gray-700 hover:text-gray-900 hover:bg-gray-100 block px-4 py-2 text-sm';
    @endphp
    
    @if ($tag === 'a')
    
        <x-a class="{{ $classes }}" {{ $attributes }}>
            {{ $slot }}
        </x-a>
    
    @else
    
        <x-button class="{{ $classes }}"> {{-- w-full text-left GETS MERGERD--}}
            {{ $slot }}
        </x-button>
        
    @endif