Isolate
#[Isolate] 属性阻止组件的请求与其他组件更新打包在一起,从而允许其并行执行。
为何打包很重要
Livewire 中每次组件更新都会触发网络请求。默认情况下,当多个组件同时触发更新时,它们会被打包到单个请求中。
不过,有时出于性能考虑需要禁用这种打包。这时就用到 #[Isolate]。
基本用法
将 #[Isolate] 属性应用到任何应发送独立请求的组件上:
php
<?php // resources/views/components/post/⚡show.blade.php
use Livewire\Attributes\Isolate;
use Livewire\Component;
use App\Models\Post;
new #[Isolate] class extends Component { // [tl! highlight]
public Post $post;
public function refreshStats()
{
// Expensive operation...
$this->post->recalculateStatistics();
}
};使用 #[Isolate] 后,该组件的请求将不再与其他组件更新打包,从而可以并行执行。
TIP
打包何时有益、何时有害
打包在大多数场景下很好,但如果某个组件执行昂贵操作,打包会拖慢整个请求。隔离该组件可让它与其他更新并行运行。
何时使用
在以下情况使用 #[Isolate]:
- 组件执行昂贵操作(复杂查询、API 调用、重计算)
- 多个组件使用 `wire:poll`,且你希望轮询间隔相互独立
- 组件监听事件,且你不希望一个慢组件阻塞其他组件
- 该组件无需与页面上其他组件协调
示例:轮询组件
下面是一个包含多个轮询组件的实际示例:
php
<?php // resources/views/components/⚡system-status.blade.php
use Livewire\Attributes\Isolate;
use Livewire\Component;
new #[Isolate] class extends Component { // [tl! highlight]
public function checkStatus()
{
// Expensive external API call...
return ExternalService::getStatus();
}
};blade
<div wire:poll.5s>
Status: {{ $this->checkStatus() }}
</div>没有 #[Isolate] 时,该组件缓慢的 API 调用会拖慢页面上其他组件。有了它,组件可独立轮询而不阻塞其他组件。
懒加载组件默认已隔离
使用 #[Lazy] 属性时,组件会自动隔离以并行加载。如有需要可以禁用此行为:
php
<?php // resources/views/components/⚡revenue.blade.php
use Livewire\Attributes\Lazy;
use Livewire\Component;
new #[Lazy(isolate: false)] class extends Component { // [tl! highlight]
// ...
};现在多个 revenue 组件会将懒加载请求打包到单个网络请求中。
权衡
优点:
- 防止慢组件阻塞其他更新
- 允许昂贵操作真正并行执行
- 独立的轮询与事件处理
缺点:
- 对服务器的网络请求更多
- 无法在同一请求中与其他组件协调
- 多个连接带来略高的服务器开销