主题
Renderless
#[Renderless] 属性在调用操作时跳过 Livewire 生命周期的渲染阶段,为不修改组件视图的操作提高性能。
基本用法
将 #[Renderless] 属性应用到任何不需要重新渲染组件的操作方法上:
php
<?php // resources/views/components/post/⚡show.blade.php
use Livewire\Attributes\Renderless;
use Livewire\Component;
use App\Models\Post;
new class extends Component
{
public Post $post;
public function mount(Post $post)
{
$this->post = $post;
}
#[Renderless] // [tl! highlight]
public function incrementViewCount()
{
$this->post->incrementViewCount();
}
};blade
<div>
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<div wire:intersect="incrementViewCount"></div>
</div>上面的示例使用 wire:intersect 在用户滚动到底部时调用 incrementViewCount()。由于应用了 #[Renderless],浏览量被记录但模板不会重新渲染——页面的任何部分都不会受到影响。
何时使用
在以下情况下使用 #[Renderless]:
- 仅执行后端操作(日志记录、分析、跟踪)
- 不修改任何影响渲染视图的属性
- 需要频繁运行而不导致不必要的重新渲染
常见用例包括:
- 跟踪用户交互(点击、滚动、页面停留时间)
- 发送分析事件
- 更新计数器或指标
- 执行后台操作
替代方法
使用 skipRender()
如果您需要有条件地跳过渲染或不想使用属性,可以在操作中直接调用 skipRender():
php
<?php // resources/views/components/post/⚡show.blade.php
use Livewire\Component;
use App\Models\Post;
new class extends Component
{
public Post $post;
public function incrementViewCount()
{
$this->post->incrementViewCount();
$this->skipRender(); // [tl! highlight]
}
};使用 .renderless 修饰符
您还可以使用 .renderless 修饰符直接从元素跳过渲染:
blade
<button type="button" wire:click.renderless="incrementViewCount">
跟踪浏览
</button>这种方法对于不想向方法添加属性的一次性情况很有用。
了解更多
有关操作和性能优化的更多信息,请参阅操作文档。