Xây dựng UI tái sử dụng cao với Blade Components & Slots

· 3 min read

Blade Components là một trong những tính năng mạnh mẽ nhất của Laravel giúp bạn tổ chức mã HTML và tái sử dụng UI một cách dễ dàng và sạch sẽ.

1. Class-based Components vs Anonymous Components

Anonymous Components

Thích hợp cho các UI tĩnh, không đòi hỏi logic chuẩn bị dữ liệu phức tạp. File component được lưu tại resources/views/components/alert.blade.php:

<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Sử dụng:

<x-alert type="error">
    Lỗi: Không thể kết nối cơ sở dữ liệu!
</x-alert>

Class-based Components

Thích hợp khi component cần logic trước khi render. Chạy lệnh php artisan make:component Alert. Nó tạo 2 file:

  • app/View/Components/Alert.php
  • resources/views/components/alert.blade.php
namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;
    public $message;

    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function render()
    {
        return view('components.alert');
    }
}

2. Quản lý Attributes với $attributes->merge()

Khi làm việc với các framework CSS như Tailwind, việc merge các class bên ngoài truyền vào với class mặc định là điều bắt buộc.

Bên trong component:

<button {{ $attributes->merge(['class' => 'bg-blue-500 text-white px-4 py-2 rounded font-bold']) }}>
    {{ $slot }}
</button>

Khi sử dụng, bạn có thể truyền thêm class và nó sẽ được ghép nối an toàn:

<x-button class="hover:bg-blue-700 mt-4">
    Lưu thay đổi
</x-button>

3. Namd Slots và Scoped Slots

Bên cạnh một biến $slot mặc định, bạn có thể tái sử dụng block phức tạp qua Name Slots.

Component modal.blade.php:

<div class="modal">
    <div class="modal-header">
        {{ $title }}
    </div>
    <div class="modal-body">
        {{ $slot }}
    </div>
    <div class="modal-footer">
        {{ $actions }}
    </div>
</div>

Sử dụng Modal:

<x-modal>
    <x-slot:title>
        Xác nhận xoá
    </x-slot>

    Bạn có chắc chắn muốn xoá bài viết này không?

    <x-slot:actions>
        <button>Hủy</button>
        <button class="text-red-500">Xoá</button>
    </x-slot>
</x-modal>

Sử dụng cấu trúc component giúp file layout của bạn gọn gàng và dễ bảo trì hơn bao giờ hết.

Bình luận