组件钩子
全局组件钩子
若要为应用中每一个组件添加功能或行为,可以使用 Livewire「组件钩子」(Component Hooks)。
组件钩子允许你定义一个类,从外部挂接到 Livewire 组件的生命周期(不在组件类本身上,也不在 trait 中)。
在看实际示例之前,先看一个通用的组件钩子类,其中列出了内部可用的全部方法:
php
use Livewire\ComponentHook;
class MyComponentHook extends ComponentHook
{
public static function provide()
{
// Runs once at application boot.
// Can be used to register any services you may need.
}
public function mount($params, $parent)
{
// Called when a component is "mounted"
//
// $params: Array of parameters passed into the component
// $parent: The parent component object if this is a nested component
}
public function hydrate($memo)
{
// Called when a component is "hydrated"
//
// $memo: An associative array of the "dehydrated" metadata for this component
}
public function boot()
{
// Called when the component boots
}
public function update($property, $path, $value)
{
// Called before the component updates...
return function () {
// Called after the component property has updated...
};
}
public function call($method, $params, $returnEarly)
{
// Called before a method on the component is called...
return function ($returnValue) {
// Called after a method is called
};
}
public function render($view, $data)
{
// Called after "render" is called but before the Blade has been rendered...
return function ($html) {
// Called after the component's view has been rendered
};
}
public function dehydrate($context)
{
// Called when a component "dehydrates"
}
public function exception($e, $stopPropagation)
{
// Called if an exception is thrown within a component...
}
}可在服务提供者(如 App\Providers\AppServiceProvider)中注册组件钩子,例如:
php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Livewire::componentHook(MyComponentHook::class);
}
// ...
}看完组件钩子的概览后,下面是一个更实用的例子:用它们为应用提供有用功能。
假设你希望任意 Livewire 动作都能返回 CSV,并自动触发文件下载。例如,可在 CreatePost 组件的 save 方法中返回 Csv:
php
use Livewire\Component;
class CreateUser extends Component
{
public $username = '';
public $email = '';
public function something()
{
return new Csv();
}
// ...
}php
<?php
namespace App;
use Livewire\ComponentHook;
class SupportCsvDownloads extends ComponentHook
{
public function call($method, $params, $returnEarly)
{
// Called before a method on the component is called...
return function ($returnValue) {
if ($returnValue instanceof Csv) {
// do something
}
};
}
}call() 返回的回调在组件方法执行完毕后运行。本例中,它可以检查每个方法的返回值,并在一处统一处理 Csv 实例。