Laravel Blade组件如何实现代码复用? (class与匿名组件)

13次阅读

Blade class 组件需定义继承 IlluminateViewComponent 的 php 类并实现 render() 方法,类须置于 app/View/Components/ 下且通过 artisan 命令生成;匿名组件则为 resources/views/components/ 下的纯 Blade 文件,通过 @props 声明属性,无需 PHP 类。

Laravel Blade组件如何实现代码复用? (class与匿名组件)

Blade class 组件:必须定义完整 PHP 类

Blade class 组件不是直接写在视图里就能用的,它要求你先创建一个继承 IlluminateViewComponent 的 PHP 类,并在其中定义 render() 方法。laravel 不会自动扫描视图目录下的 PHP 文件——类必须放在 app/View/Components/ 下,且需通过 php artisan make:component alert 命令生成(否则命名空间、目录结构或自动发现容易出错)。

常见错误是把 class 组件当成普通模板直接 @include,结果报错 Class "AppViewComponentsAlert" not found。正确做法是:运行命令生成类 → 在 render() 中返回 view('components.alert') → 然后在 Blade 中用 调用。

参数传递靠构造函数public 属性,例如:

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'); }

}

注意:构造函数参数不能是可选类型(如 ?string),否则 Laravel 无法解析依赖;$message 默认空字符串是安全的,但 NULL 会导致绑定失败。

Blade 匿名组件:零 PHP 类,直接复用视图文件

匿名组件本质就是一个带 @props 声明的 Blade 文件,无需 PHP 类、无需注册、不走服务容器。它适合轻量、无逻辑、纯展示型复用,比如按钮、卡片外壳、表单字段包装器。

使用前提是:文件必须放在 resources/views/components/ 目录下(如 resources/views/components/card.blade.php),且文件名决定标签名(card.blade.php)。路径层级不影响调用,但不能嵌套子目录(components/ui/card.blade.php 不会被识别)。

@props 必须写在文件顶部,且只能出现一次;它接收传入的属性并自动转为变量:

@props(['title' => '', 'border' => true]) 

merge(['class' => 'p-4 rounded']) }}> @if($title)

{{ $title }}

@endif {{ $slot }}

text=ZqhQzanResources