Laravel 8 传递数据到组件中

2021-07-17 16:51 更新

您可以使用 HTML 属性传递数据到 Blade 组件中。普通的值可以通过简单的 HTML 属性来传递给组件。PHP 表达式和变量应该通过以 : 字符作为前缀的变量来进行传递:

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

您应该在类的构造器中定义组件的必要数据。在组件的视图中,组件的所有 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;

    /**
     * 创建一个组件实例。
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    /**
     * 获取组件的视图 / 内容
     *
     * @return \Illuminate\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

渲染组件时,您可以回显变量名来显示组件的 public 变量的内容:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号