0

我正在尝试学习 laravel,并且正在尝试使用一些组件。

我创建了一个布局组件,其中包括导航栏并且它工作正常。

我仍然在控制器中使用键/值数组,因为我还没有研究数据库。

现在我正在尝试创建一个动态卡片组件,并在一个名为 card.blade.php 的新组件中编写了以下内容:

<div class="card" style="width: 18rem;">
  <img class="card-img-top" src="{{$img}}" alt="Card image cap">
  <div class="card-body">
    <h5 class="card-title">{{$title}}</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

在页面上,我想显示这些卡片(shop.blade.php),我正在执行以下操作:

<x-layout>
    <div class="container">
        <div class="row">
            @foreach($products as $product)
                <div class="col-4">
                  <x-card
                  img="{{$product['img']}}"
                  title = "{{$product['name']}}"
                  />
                </div>
            @endforeach
        </div>
    </div>
</x-layout>

但是当我运行我的本地主机时,卡片不会在浏览器上呈现,或者更好的是,它们没有任何大小(0x0)。我可以从“检查”中看到它采用正确的参数,并且从 forEach 中正确生成。

我试图运行相同但没有任何动态变量,并且卡片的大小正确显示。

就像当我尝试将变量关联起来时,它们会失去维度。

有没有人可以帮助我解决这个问题?:D

太感谢了

4

1 回答 1

0

一个组件由两部分组成:一个类和一个视图。

确保创建了文件夹中调用的CardApp/View/Components。如果是这样,请检查 title 和 img 属性是否存在并且它们是公开的。

App/View/Components/Card.php:




namespace App\View\Components;

use Illuminate\View\Component;

class Card extends Component
{
    public $img;
    public $title;

    public function __construct($img, $title)
    {
        $this->img = $img;
        $this->title = $title;
    }

    public function render()
    {
        return view('components.card');
    }
}
于 2021-10-24T11:50:03.017 回答