如果我們有一些元件想要重複使用,Laravel 也提供了方法讓我們可以方便使用。
首先透過指令建立新的元件:
php artisan make:component Alert
指令完成後就會在 app/View/Components 和 resources/views/components 建立新的元件,檔名會是你設定的 component 名字 Alert.php 和 alert.blade.php
alert.blade.php 會是 UI 的樣子,而 Alert.php 預設會長這樣:
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
public function __construct()
{
}
public function render()
{
return view('components.alert');
}
}
接下來我把 blade 那個檔案寫成 bootstrap 內建的 component:
<div class="alert alert-primary" role="alert">
This is a primary alert—check it out!
</div>
這樣就可以設定好 component 了,要使用的話只要像這樣就可以在 blade 裡面重複使用了:
<x-alert />
x- 後面對應的就是設定的 component 名稱。
接下來講怎麼把變數丟到 component 內,要把變數丟進去可以參考下面的寫法:
<x-alert type="danger" :message="$message"/>
如果要丟進去變數前面沒有 : 就是固定的值,加 $ 的話則是會從程式裡抓變數進去。
接下來在 Alert.php 裡建立變數,並在建構的時候賦予值:
public $type;
public $message;
public function __construct($type, $message)
{
$this->type = $type;
$this->message = $message;
}
並把 blade 改成這樣:
<div class="alert alert-{{ $type }}">
{{ $message }}
</div>
我這邊也改成把變數這樣丟進去:
<x-alert type="danger" message="這邊是錯誤訊息"/>
就能看到紅色的 alert 元件。
如果設定的變數是複合字,要使用 camelCase 像這樣:
public function __construct($alertType)
{
$this->alertType = $alertType;
}
丟變數進去的話則是可以寫成這樣:
<x-alert alert-type="danger" />