【问题标题】:How define variable in laravel component如何在 laravel 组件中定义变量
【发布时间】:2021-03-02 19:40:32
【问题描述】:

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

我的代码得到了未定义的变量:覆盖错误

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

item-h.blade.php

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

item-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');
    }
}

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

谢谢

【问题讨论】:

  • 您需要在Item_h 构造函数中使用$this-&gt;covers 而不是$covers
  • @remul 我之前测试过,没用

标签: php variables components laravel-8


【解决方案1】:

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

    <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');
    }
}

我相信这会解决您的问题

【讨论】:

  • 此外,如果您想将封面作为变量发送,您也可以这样做,您也可以将 $covers 更改为 #this->covers;这将完美地工作
猜你喜欢
  • 2020-07-02
  • 2017-08-29
  • 2017-11-15
  • 2021-03-26
  • 2015-02-04
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2021-12-10
相关资源
最近更新 更多