从(Laravel 8)Blade模板文件中调用函数

3
我有一个名为OrderBox.php的刀片组件,位于app/View/Components中。 我可以从orderbox.blade.php模板文件访问它的几个公共属性。
            <x-orderbox
                    :id="$id"
                    ....
            ></x-orderbox>

然而,在 OrderBox.php 组件文件中,存在一个名为 getShortTextByStatus($statusCode) 的公共函数, 当我在 orderbox.blade.php 模板中调用此函数时

{{ $getShortTextByStatus('EDIT') }}

我遇到了 Undefined variable: shortTextByStatus 错误。

我按照这个链接的步骤进行操作: https://laravel.com/docs/8.x/blade#component-methods 但是所有东西看起来都一样,我错过了什么?

编辑:

如果我删除 $ 符号,我会得到 Call to undefined function getShortTextByStatus() 的错误。

{{ getShortTextByStatus('EDIT') }}

OrderBox.php

class OrderBox extends Component
{

    public $id;
    ....

    public function __construct()
    {
    //
    }

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

    public function getShortTextByStatus($statusCode)
    {
       return 'TEST';
    }

}

编辑2:

我注意到x-orderbox实际上应该是x-order-box。

<x-order-box
    :id="$id"
     ....
></x-order-box>

这样,{{ $getShortTextByStatus("EDIT") }} 能够正常工作了!

但是:

它不会传递像:id="$id"这样的属性。

something="static" 

因此,public $id; 或 public $something 将为空....


你能分享一下 OrderBox.php 文件吗? - Wahyu Kristianto
@GJasonSharma - 我确实是从内部调用它的,我已经在文本中突出显示了那部分。 - pszaba
我收到了“Undefined variable: shortTextByStatus”错误,这是你问题或代码中的拼写错误吗?应该使用$getShortTextByStatus()而不是$shortTextByStatus(),这些函数需要使用$符号。 - Gert B.
1
你尝试将它重命名为不以 get 开头的名称了吗?这可能会让 Laravel 感到困惑。只是猜测。 - brombeer
1
要使用 :id 传递 $id,您必须在构造函数中传递它:public function __construct($id) { 并使用 $this->id = id; 进行设置。 - Gert B.
显示剩余5条评论
1个回答

0

所以我在这里犯了几个错误

首先,如果组件名称是OrderBox,那么

标签应该是

<x-order-box></x-order-box>

然后,如果您想将数据传递给组件(OrdeBox),您需要将属性添加到构造函数中 - 特别感谢评论区的@gert-b(Gert B)

class OrderBox extends Component
{

    public $id;
    public $otherId;
    ....

    public function __construct($id, $otherId)
    {
        $this->id = $id;
        $this->otherId;
    }

    ...
    ...
}

出于某种原因,我认为只有必填属性才会进入构造函数。

别忘了,组件类中的属性是驼峰式命名,例如 public $otherId; 但在模板中,它是短横线命名:other-id

<x-order-box
    id="1"
    :other-id="$someVariable"
></x-order-box>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接