Skip to content
全部文档

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">
    Track View
</button>

这种方式适合一次性场景,无需给方法添加属性。

了解更多

关于操作与性能优化的更多信息,请参阅操作文档