Laravel 8 傳遞數(shù)據(jù)到組件中

2021-07-17 16:51 更新

您可以使用 HTML 屬性傳遞數(shù)據(jù)到 Blade 組件中。普通的值可以通過簡單的 HTML 屬性來傳遞給組件。PHP 表達式和變量應(yīng)該通過以 : 字符作為前綴的變量來進行傳遞:

<x-alert type="error" :message="$message"/>

您應(yīng)該在類的構(gòu)造器中定義組件的必要數(shù)據(jù)。在組件的視圖中,組件的所有 public 類型的屬性都是可用的。不必通過組件類的 render 方法傳遞:

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    /**
     * alert 類型。
     *
     * @var string
     */
    public $type;

    /**
     * alert 消息。
     *
     * @var string
     */
    public $message;

    /**
     * 創(chuàng)建一個組件實例。
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    /**
     * 獲取組件的視圖 / 內(nèi)容
     *
     * @return \Illuminate\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

渲染組件時,您可以回顯變量名來顯示組件的 public 變量的內(nèi)容:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號