Blade组件和插槽是Laravel实现UI模块化的核心机制;组件封装结构与默认行为,插槽支持默认内容、具名插槽及作用域插槽,通过php artisan make:component生成。

Blade组件和插槽是Laravel中组织可复用视图代码的核心方式,它们让UI模块化、逻辑清晰、维护更轻松。关键在于:组件封装结构与默认行为,插槽(slot)负责动态注入内容,支持默认内容、具名插槽和作用域插槽。
创建和使用基础组件(无插槽)
运行命令生成组件类和视图:
php artisan make:component Alert
会在 app/View/Components/Alert.php 和 resources/views/components/alert.blade.php 中生成文件。
在组件类中可定义公共属性(如类型、消息),并在视图中使用:
// app/View/Components/Alert.php
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
public string $type;
public string $message;
public function __construct(string $type = 'info', string $message = '')
{
$this->type = $type;
$this->message = $message;
}
public function render()
{
return view('components.alert');
}
}
// resources/views/components/alert.blade.php
<div class="alert alert-{{ $type }}">
{{ $message }}
</div>
在任意Blade模板中使用:
<x-alert type="error" message="操作失败,请重试!" />
使用默认插槽(slot)注入内容
把组件视图中的 {{ $slot }} 当作“内容占位符”,外部传入的内容会自动填充进去。
修改 alert.blade.php:
<div class="alert alert-{{ $type }}">
{{ $slot }}
</div>
调用时改用双标签写法:
<x-alert type="success">
用户已成功创建!
</x-alert>
此时“用户已成功创建!”就会渲染在 {{ $slot }} 的位置。
使用具名插槽(named slot)区分多区域内容
适合有标题、正文、操作按钮等不同区域的组件,比如卡片(Card):
php artisan make:component Card
在 resources/views/components/card.blade.php 中:
<div class="card">
<div class="card-header">
{{ $header ?? '默认标题' }}
</div>
<div class="card-body">
{{ $slot }}
</div>
<div class="card-footer">
{{ $footer }}
</div>
</div>
注意:{{ $header }} 和 {{ $footer }} 是具名插槽,需在使用时显式指定:
<x-card>
<x-slot name="header">
用户信息
</x-slot>
<p>姓名:张三</p>
<p>邮箱:zhang@example.com</p>
<x-slot name="footer">
<button class="btn btn-primary">编辑</button>
</x-slot>
</x-card>
具名插槽支持默认值(如 {{ $header ?? '默认标题' }}),未传入时显示后备内容。
使用作用域插槽(scoped slot)传递数据给插槽
当组件内部需要向插槽暴露变量(比如循环项、状态等),可用作用域插槽。以列表组件为例:
php artisan make:component UserList
组件类中传入用户集合:
public function __construct(public array $users) {}
视图中用 @props 接收,并通过 <x-slot> 的 :name 绑定属性:
<ul>
@foreach ($users as $user)
<li>
<x-slot name="item" :user="$user">
<span class="user-name">{{ $user['name'] }}</span>
</x-slot>
</li>
@endforeach
</ul>
但更标准的做法是:在组件视图里用 {{ $slot($user) }} 调用插槽并传参,然后外部用函数式语法接收:
修改 user-list.blade.php:
<ul>
@foreach ($users as $user)
<li>
{{ $slot($user) }}
</li>
@endforeach
</ul>
使用时(注意括号语法):
<x-user-list :users="$users">
@foreach ($users as $user)
<x-slot:default :user="$user">
<strong>{{ $user['name'] }}</strong> — {{ $user['email'] }}
</x-slot>
@endforeach
</x-user-list>
更简洁写法(推荐):
<x-user-list :users="$users">
@foreach ($users as $user)
<x-slot:default :user="$user">
<span>{{ $user['name'] }}</span>
</x-slot>
@endforeach
</x-user-list>
或者直接用闭包风格(Laravel 9+ 支持):
<x-user-list :users="$users">
@foreach ($users as $user)
{{ $slot($user) }}
@endforeach
</x-user-list>
⚠️ 实际项目中建议统一用具名插槽 + 属性绑定,语义更清晰、IDE支持更好。
基本上就这些。组件封装结构,插槽承载内容,具名插槽分区域,作用域插槽传数据——掌握这四层,就能写出高内聚、易复用的Blade UI模块。










