Laravel:Blade 组件 101
关注我!:关注@EricTheCoder_
我会定期在 Dev.to 上发布文章,如果您不想错过任何内容,请点击关注。
您也可以在 Twitter 上关注我:关注 @justericchapman
Blade 组件
Blade 组件是 blade 模板的一个子集,允许您创建新的自定义、可重用、封装的 PHP 和 HTML。
例如,你可能想创建一个导航栏,用于你的多个应用页面。那么,你可以将导航栏构建为一个组件,并可以在任何需要的地方重复使用该组件。
创建后,可以使用与任何 html 标签相同的语法来调用组件:
<html>
<body>
<x-navbar/>
</body>
</html>
基于类的组件
基于类的组件由封装组件逻辑的php文件和模板文件组成。
要创建基于类的组件,您可以使用 Artisan 命令 make:component
php artisan make:component Alert
此命令将创建两个文件:
app\View\Components\Alert.php
resources\views\components\alert.blade.php
Alert.php 文件是一个继承自 Component 的类
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
public function __construct()
{
//
}
public function render()
{
return view('components.alert');
}
}
alert.blade.php 模板文件是一个空容器:
<div>
</div>
我们来举个例子。最终目标是显示一条警报消息,并根据警报类型(错误或成功)设置消息样式。
当组件被创建时,您可以使用 x-name 语法调用您的新组件:
<x-alert type="error" :message="$message"/>
x- 是一个约定,告诉 Laravel 渲染指定的组件名称。
:message 中的“:”前缀告诉 Laravel,props 的内容将绑定到 php 表达式/变量。
当您在组件名称前附加 x- 时,Laravel 就知道在哪里找到您的组件。
:type 和 :message 是传递给组件的数据
您可以在组件类文件中检索这些值:
<?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');
}
}
在组件模板中,您可以通过按名称回显变量来显示组件公共变量的内容:
<div class="alert alert-{{ $type }}">
{{ $message }}
</div>
组件属性
有时您可能需要指定额外的 HTML 属性,例如不属于组件数据的类。
<x-alert type="error" :message="$message" class="mt-4"/>
如果您想将这些附加属性传递到组件模板的根元素,您可以使用 $attributes 变量。
<div {{ $attributes }}>
</div>
这将呈现为:
<div class="mt-4">
</div>
如果您的 div 中已经存在类属性,您可以使用 $attributes->merge 将两者合并在一起。
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
{{ $message }}
</div>
这将呈现为:
<div class="alert alert-error mt-4">
</div>
投币口
你经常需要通过“插槽”向组件传递额外的内容。组件插槽通过回显 $slot 变量来渲染。
您可以将内容传递给组件:
<x-alert>
This is a alert
</x-alert>
插槽内容现在可以在我们的组件模板中的任何位置使用:
<div class="alert alert-danger">
{{ $slot }}
</div>
您可以通过以下命名来传递多个内容(插槽):
<x-alert>
<x-slot name="title">This is a alert</x-slot>
<x-slot name="sub">This is a sub message</x-slot>
</x-alert>
这些名称槽内容可以在我们的组件模板中的任何位置使用:
<div>
{{ $title }}
{{ $sub }}
</div>
结论
今天就到这里。明天旅程继续,如果你想了解更多关于组件的知识,请阅读 Laravel 官方文档:https://laravel.com/docs/8.x/blade#components
如果你想确保不错过任何内容,请点击这里或在 Twitter 上关注我!
关注我!:关注@EricTheCoder_
文章来源:https://dev.to/ericchapman/laravel-blade-components-5c9c