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">Follow</button>
</div>

user() 方法像属性一样使用 $this->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; // Only queries database once
    }
};

这允许你自由访问派生值而不必担心性能影响。

清除缓存

如果底层数据在请求期间发生变化,你可以使用 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); // Clear cache [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 hours [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 访问它们将导致错误。

了解更多

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

参考

php
#[Computed(
    bool $persist = false,
    int $seconds = 3600,
    bool $cache = false,
    ?string $key = null,
    mixed $tags = null,
)]
参数类型默认值描述
$persistboolfalse为同一组件实例跨请求缓存值
$secondsint3600缓存值的持续时间(秒)
$cacheboolfalse跨所有组件实例缓存值
$key?stringnull自定义缓存键(如果未提供则自动生成)
$tagsmixednull缓存标签(需要支持标签的缓存驱动)