公告: 旧版文档请移步 -> http://v2.laravel-filament.cn/docs

Languages

Version

Theme

Widgets

统计概览 Widget

概述

Filament 自带一个 "统计概览" Widget 模板,用来在单个 Widget 中展示许多不同状态,而无需编写自定义视图。

使用以下命令创建 Widget:

php artisan make:filament-widget StatsOverview --stats-overview

该命令将会创建一个新的 StatsOverview.php 文件。打开该文件,然后在 getStats() 返回 Stat 实例:

<?php
 
namespace App\Filament\Widgets;
 
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
 
class StatsOverview extends BaseWidget
{
protected function getStats(): array
{
return [
Stat::make('Unique views', '192.1k'),
Stat::make('Bounce rate', '21%'),
Stat::make('Average time on page', '3:12'),
];
}
}

现在,你可以到仪表盘上去查看 Widget 了。

添加描述及图标

你可以使用 description() 方法提供额外的描述信息,同时也可以通过 descriptionIcon() 添加描述图标:

protected function getStats(): array
{
return [
Stat::make('Unique views', '192.1k')
->description('32k increase')
->descriptionIcon('heroicon-m-arrow-trending-up'),
Stat::make('Bounce rate', '21%')
->description('7% increase')
->descriptionIcon('heroicon-m-arrow-trending-down'),
Stat::make('Average time on page', '3:12')
->description('3% increase')
->descriptionIcon('heroicon-m-arrow-trending-up'),
];
}

修改 Stat 颜色

你也可以通过 color() (dangergrayinfoprimarysuccesswarning) 指定 Stat 颜色:

protected function getStats(): array
{
return [
Stat::make('Unique views', '192.1k')
->description('32k increase')
->descriptionIcon('heroicon-m-arrow-trending-up')
->color('success'),
Stat::make('Bounce rate', '21%')
->description('7% increase')
->descriptionIcon('heroicon-m-arrow-trending-down')
->color('danger'),
Stat::make('Average time on page', '3:12')
->description('3% increase')
->descriptionIcon('heroicon-m-arrow-trending-up')
->color('success'),
];
}

添加额外 HTML 属性到 Stat

使用 extraAttributes() 方法,你可以将额外的 HTML 属性传入 Stat 中:

protected function getStats(): array
{
return [
Stat::make('Processed', '192.1k')
->color('success')
->extraAttributes([
'class' => 'cursor-pointer',
'wire:click' => "\$dispatch('setStatusFilter', { filter: 'processed' })",
]),
// ...
];
}

本例中,我们刻意转义了 $dispatch() 中的 $,因为它不是 PHP 变量,需要直接传入到 HTML 中。

添加图表到 Stat

你也可以添加或者链式调用 chart() 到每个 Stat,以提供历史数据。chart() 方法接收一组要绘制的点形成的数组:

protected function getStats(): array
{
return [
Stat::make('Unique views', '192.1k')
->description('32k increase')
->descriptionIcon('heroicon-m-arrow-trending-up')
->chart([7, 2, 10, 3, 15, 4, 17])
->color('success'),
// ...
];
}

实时更新统计数据(轮询)

默认情况下,统计概述 Widget 每 5 秒钟刷新一次数据。

你可以通过重写类上的 $pollingInterval 属性自定义间隔时间:

protected static ?string $pollingInterval = '10s';

或者,也可以完全禁用轮询:

protected static ?string $pollingInterval = null;

禁用懒加载

默认情况下,Widget 使用懒加载。这意味着只有当它们在页面中可见时才会加载。

要禁用该行为,你可以在 Widget 类中重写 $isLazy 属性:

protected static bool $isLazy = false;
Edit on GitHub

Still need help? Join our Discord community or open a GitHub discussion

上一页
安装