Skip to content

Computed

#[Computed] 属性允许您创建在请求期间缓存的派生属性,在多次访问昂贵操作时提供性能优势。

基本用法

#[Computed] 属性应用到任何方法上,将其转换为缓存属性:

php
<?php // resources/views/components/user/⚡show.blade.php

use Livewire\Attributes\Computed;
use Livewire\Component;
use App\Models\User;

new class extends Component
{
    public $userId;

    #[Computed] // [tl! highlight]
    public function user()
    {
        return User::find($this->userId);
    }

    public function follow()
    {
        Auth::user()->follow($this->user);
    }
};
blade
<div>
    <h1>{{ $this->user->name }}</h1>
    <span>{{ $this->user->email }}</span>

    <button wire:click="follow">关注</button>
</div>

使用 $this->user 像访问属性一样访问 user() 方法。第一次调用时,结果会被缓存并在请求的其余部分重用。

必须在模板中使用 $this

与普通属性不同,计算属性必须通过模板中的 $this 访问。例如,使用 $this->posts 而不是 $posts

性能优势

计算属性在请求期间缓存其结果。如果您多次访问 $this->posts,底层方法只会执行一次:

php
<?php // resources/views/components/post/⚡index.blade.php

use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Component;

new class extends Component
{
    #[Computed] // [tl! highlight]
    public function posts()
    {
        return Auth::user()->posts; // 只查询一次数据库
    }
};

这使您可以自由访问派生值,而无需担心性能影响。

清除缓存

如果底层数据在请求期间发生变化,您可以使用 unset() 清除缓存:

php
<?php // resources/views/components/post/⚡index.blade.php

use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Component;

new class extends Component
{
    #[Computed]
    public function posts()
    {
        return Auth::user()->posts;
    }

    public function createPost()
    {
        if ($this->posts->count() > 10) {
            throw new \Exception('Maximum post count exceeded');
        }

        Auth::user()->posts()->create(...);

        unset($this->posts); // 清除缓存 [tl! highlight]
    }
};

创建新帖子后,unset($this->posts) 会清除缓存,以便下次访问时检索更新的数据。

跨请求缓存

默认情况下,计算属性仅在单个请求内缓存。要跨多个请求缓存,请使用 persist 参数:

php
#[Computed(persist: true)] // [tl! highlight]
public function user()
{
    return User::find($this->userId);
}

这将缓存值 3600 秒(1 小时)。您可以自定义持续时间:

php
#[Computed(persist: true, seconds: 7200)] // 2 小时 [tl! highlight]

跨所有组件缓存

要在应用程序中的所有组件实例之间共享缓存值,请使用 cache 参数:

php
use Livewire\Attributes\Computed;
use App\Models\Post;

#[Computed(cache: true)] // [tl! highlight]
public function posts()
{
    return Post::all();
}

您可以选择设置自定义缓存键:

php
#[Computed(cache: true, key: 'homepage-posts')] // [tl! highlight]

何时使用

计算属性在以下情况下特别有用:

  • 有条件地访问昂贵数据 - 仅在模板中实际使用该值时才查询数据库
  • 使用内联模板 - 没有机会通过 render() 传递数据
  • 省略 render 方法 - 遵循 v4 的单文件组件约定
  • 多次访问相同值 - 自动缓存可防止冗余查询

限制

不支持 Form 对象

计算属性不能在 Livewire\Form 对象上使用。尝试通过 $form->property 访问它们将导致错误。

了解更多

有关计算属性、缓存策略和高级用例的详细信息,请参阅计算属性文档