首页 > 解决方案 > 如何在 laravel 组件中定义变量

问题描述

我使用laravel 8 组件,根据文档可以传递数据并使用它。但我需要一些修改传递的数据作为可以在组件中使用的变量

我的代码有未定义的变量:覆盖错误

<x-item_h :item="$item"/>

项目-h.blade.php

<div class="item-h">
    {{$item}}
    {{$covers}}
</div>

项目-h.php

class Item_h extends Component
{
    public $item;
    public $covers;

    public function __construct($item )
    {
        $this->item = $item;

        if ($item->getCover->count() > 0) {
            $covers = $item->getCover;
        } else {
            $covers = $item->artists->getCover;
        }
        
    }

    public function render()
    {
        return view('components.item_h');
    }
}

那么如何在组件中定义可以在其中使用的变量呢?

谢谢

标签: phpvariablescomponentslaravel-8

解决方案


首先,当您像这样调用组件时,您需要添加封面。

    <x-item_h :item="$item" covers/>

现在更新构造函数并添加覆盖您选择的默认值,这样即使您忘记给它赋值,它也不会使您的视图崩溃

class Item_h extends Component
{
    public $item;
    public $covers;

    public function __construct($item ,$covers={{REPLACE WITH DEFAULT VALUE}})
    {
        $this->item = $item;
        $this->covers = $covers; 
        if ($item->getCover->count() > 0) {
            $covers = $item->getCover;
        } else {
            $covers = $item->artists->getCover;
        }
        
    }

    public function render()
    {
        return view('components.item_h');
    }
}

我相信这会解决你的问题


推荐阅读