Laravel 7 中的 Blade 视图组件初探
Laravel 的组件功能之前就已经以 Blade 指令的形式存在了。(文档链接)
但是,在 Laravel 7 中,组件功能被提升到了一个全新的高度。
让我们深入了解一下。
撰写本文时 Laravel 7 尚未发布,如果您想跟着教程操作,可以使用以下命令下载。
laravel new projectname --dev
创建组件
Artisan新增了一个命令,可以轻松创建组件:
php artisan make:component Alert
这条命令会创建两个文件:
- 类文件(
App\View\Components\Alert.php)
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}
- 刀片锉刀(
resources/views/components/alert.blade.php)
<div>
<!-- He who is contented is rich. - Laozi -->
</div>
让我们修改这段 HTML 代码,以便在渲染时可以看到这个组件的实际效果。
<div>
<h3>Alert Component</h3>
</div>
渲染组件
组件旨在用于 Blade 模板中。在 Blade 文件中使用组件有其特殊的语法。
x-后面跟着组件类的kebab 命名法名称。
<x-alert />
让我们Alert在以下情况下使用我们的组件:welcome.blade.php
<div class="content">
<div class="title m-b-md">
Laravel
</div>
<div>
<x-alert/>
</div>
</div>
自动发现
Laravel 可以自动发现app/View/Components目录中的组件resources/views/components。
但如果组件嵌套在不同的目录中呢App\View\Components\Alerts\Success.php?
我们可以使用
.符号来表示目录嵌套。
<x-alerts.success />
将数据传递给组件
我们可以通过HTML属性传递数据。这类似于传递propsVue组件的数据。
- 原始值或硬编码值
<x-alert type="error" />
- 变量和表达式应带有
:前缀。
<x-alert :message="$message" />
在组件类中,应该通过构造函数提供这些数据。
class Alert extends Component
{
public string $type;
public string $message;
public function __construct(string $type, string $message)
{
$this->type = $type;
$this->message = $message;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.alert');
}
}
请注意,这两个属性都设置为public。
所有公共属性都将可供组件的视图文件使用。您无需通过
render()方法将数据传递给视图。
alert.blade.php可以这样使用这些属性:
<div>
<div class="alert alert-{{$type}}">
<h3>{{$message}}</h3>
</div>
</div>
与此主题相关的其他内容不多:
- 匿名组件
- 访问公共方法目前还在讨论中,但我认为我们可以在“深入探讨”的文章中详细介绍🤷🏻♂️
之所以称之为“第一印象”,是因为我一边写这篇文章一边还在看文档😂文档链接
请在下方评论区告诉我您对Blade 视图组件的看法。
文章来源:https://dev.to/zubairmohsin33/first-look-at-blade-view-components-in-laravel-7-1cb2
