Laravel 7: 在 Blade Components 中使用自定义函数

Laravel

借助 Laravel 7 的模版组件,你可以在组件的视图文件中调用 公有 函数。让我们看一下旧版的 Alert 组件的例子。

class Alert extends Component
{
    public string $type;

    public string $message;

    public function __construct(string $type, string $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

现在,让我们在类中添加一个函数/方法 customFunction  :

class Alert extends Component
{
    public string $type;

    public string $message;

    public function __construct(string $type, string $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function customFunction(): string
    {
        return "string from a custom function component";
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

调用函数

现在假设我们要在 alert.blade.php 中调用该方法。就像我们在组件的视图文件中使用 公有属性 一样简单。

<div>
    <div class="alert alert-{{$type}}">
        <h3>{{$message}}</h3>
        <span>{{ $customFunction }}</span>
    </div>
</div>

传递参数

如果我们需要传递一些参数该怎么办? 非常简单 🙈

<div>
    <div class="alert alert-{{$type}}">
        <h3>{{$message}}</h3>
        <span>{{ $customFunction('custom param') }}</span>
    </div>
</div>

在我们的类文件中:

class Alert extends Component
{
    public string $type;

    public string $message;

    public function __construct(string $type, string $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function customFunction(string $param): string
    {
        return "string from a custom function component and a " . $param;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

在评论中让我知道你是怎么使用的 👇🏼

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/zubairmohsin33/laravel-7-...

译文地址:https://learnku.com/laravel/t/41768

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!