Skip to content
全部文档

Lazy

#[Lazy] 属性使组件仅在进入视口可见时才加载,防止慢速组件阻塞初始页面渲染。

基本用法

#[Lazy] 属性应用到任何应懒加载的组件上:

php
<?php // resources/views/components/⚡revenue.blade.php

use Livewire\Attributes\Lazy;
use Livewire\Component;
use App\Models\Transaction;

new #[Lazy] class extends Component { // [tl! highlight]
    public $amount;

    public function mount()
    {
        // Slow database query...
        $this->amount = Transaction::monthToDate()->sum('amount');
    }
};
?>

<div>
    Revenue this month: {{ $amount }}
</div>

使用 #[Lazy] 时,组件最初渲染为空的 <div></div>,进入视口时再加载——通常是在用户滚动到它时。

Lazy 与 Defer

Livewire 提供两种延迟组件加载的方式:

  • 懒加载(#[Lazy] - 组件在进入视口可见时加载(用户滚动到它们时)
  • 延迟加载(#[Defer] - 组件在初始页面加载完成后立即加载

对首屏以下、用户可能不会滚动到的组件使用懒加载。对始终可见但希望在页面渲染后再加载的组件使用 defer。

渲染占位符

默认情况下,组件加载前 Livewire 会渲染空的 <div></div>。你可以使用 placeholder() 方法提供自定义占位符:

php
<?php // resources/views/components/⚡revenue.blade.php

use Livewire\Attributes\Lazy;
use Livewire\Component;
use App\Models\Transaction;

new #[Lazy] class extends Component {
    public $amount;

    public function mount()
    {
        $this->amount = Transaction::monthToDate()->sum('amount');
    }

    public function placeholder() // [tl! highlight:start]
    {
        return <<<'HTML'
        <div>
            <div class="animate-pulse bg-gray-200 h-20 rounded"></div>
        </div>
        HTML;
    } // [tl! highlight:end]
};
?>

<div>
    Revenue this month: {{ $amount }}
</div>

在组件进入视口并加载之前,用户会看到骨架占位符。

WARNING

占位符元素类型需匹配

若占位符的根元素是 <div>,组件也必须使用 <div> 元素。

打包请求

默认情况下,懒加载组件通过独立的网络请求并行加载。要将多个懒加载组件打包到单个请求中,请使用 bundle 参数:

php
<?php // resources/views/components/⚡revenue.blade.php

use Livewire\Attributes\Lazy;
use Livewire\Component;

new #[Lazy(bundle: true)] class extends Component { // [tl! highlight]
    // ...
};

现在,若页面上有十个 revenue 组件,全部十个将通过单个打包的网络请求加载,而不是十个并行请求。

替代方式

使用 lazy 参数

除了属性,你也可以用 lazy 参数懒加载特定组件实例:

blade
<livewire:revenue lazy />

当你只想懒加载某个组件的部分实例时,这种方式很有用。

覆盖属性

若组件有 #[Lazy],但某些情况下希望立即加载,可以覆盖它:

blade
<livewire:revenue :lazy="false" />

何时使用

在以下情况使用 #[Lazy]

  • 组件包含会拖慢页面加载的慢操作(数据库查询、API 调用)
  • 组件在首屏以下,用户可能不会滚动到
  • 希望通过更快显示页面来提升感知性能
  • 单页上有多个昂贵的组件

了解更多

关于懒加载的完整文档(含占位符、打包策略与传递 props),请参阅懒加载文档

参考

php
#[Lazy(
    bool|null $bundle = null,
)]
参数类型默认值说明
$bundlebool|nullnull将多个懒加载组件打包到单个网络请求中