Laravel 7: 在 Blade Components 中使用自定义函数
借助 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 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: