主题
Isolate
#[Isolate] 属性防止组件的请求与其他组件更新捆绑在一起,允许它并行执行。
基本用法
将 #[Isolate] 属性应用到任何应该发送隔离请求的组件上:
php
<?php // resources/views/components/post/⚡show.blade.php
use Livewire\Attributes\Isolate;
use Livewire\Component;
use App\Models\Post;
#[Isolate] // [tl! highlight]
new class extends Component
{
public Post $post;
public function refreshStats()
{
// 昂贵的操作...
$this->post->recalculateStatistics();
}
};使用 #[Isolate],此组件的请求将不再与其他组件更新捆绑在一起,允许它们并行执行。
请求捆绑的工作原理
默认情况下,当多个组件同时触发更新时,Livewire 将它们捆绑到单个网络请求中。这减少了服务器负载并启用了响应式属性和可模型化绑定等功能。
但是,如果组件执行昂贵的操作,捆绑可能会减慢整个请求。隔离该组件允许它与其他更新并行运行。
何时使用
在以下情况下使用 #[Isolate]:
- 组件执行昂贵的操作(复杂查询、API 调用、繁重计算)
- 多个组件使用
wire:poll,您希望独立的轮询间隔 - 组件监听事件,您不希望一个慢速组件阻塞其他组件
- 组件不需要与页面上的其他组件协调
示例:轮询组件
以下是包含多个轮询组件的实际示例:
php
<?php // resources/views/components/⚡system-status.blade.php
use Livewire\Attributes\Isolate;
use Livewire\Component;
#[Isolate] // [tl! highlight]
new class extends Component
{
public function checkStatus()
{
// 昂贵的外部 API 调用...
return ExternalService::getStatus();
}
};blade
<div wire:poll.5s>
状态:{{ $this->checkStatus() }}
</div>如果没有 #[Isolate],此组件的慢速 API 调用会延迟页面上的其他组件。使用它后,组件独立轮询而不会阻塞其他组件。
Lazy 组件默认是隔离的
使用 #[Lazy] 属性时,组件会自动隔离以并行加载。如果需要,您可以禁用此行为:
php
<?php // resources/views/components/⚡revenue.blade.php
use Livewire\Attributes\Lazy;
use Livewire\Component;
#[Lazy(isolate: false)] // [tl! highlight]
new class extends Component
{
// ...
};现在多个 revenue 组件将把它们的延迟加载请求捆绑到单个网络请求中。
权衡
优点:
- 防止慢速组件阻塞其他更新
- 允许真正并行执行昂贵的操作
- 独立的轮询和事件处理
缺点:
- 到服务器的网络请求更多
- 无法在同一请求中与其他组件协调
- 多个连接的服务器开销略高
了解更多
有关请求捆绑和性能优化的更多信息,请参阅请求捆绑文档。