在 Livewire 组件中添加表格
准备 Livewire 组件
首先,生成新的 Livewire 组件:
php artisan make:livewire ListProducts
然后,在页面中渲染 Livewire 组件:
@livewire('list-products')
此外,你可以使用全页 Livewire 组件:
use App\Livewire\ListProducts;
use Illuminate\Support\Facades\Route;
Route::get('products', ListProducts::class);
添加表格
添加表格到 Livewire 组件类需要完成 3 个任务:
- 实现
HasTable和HasForms接口,并且使用InteractsWithTable和InteractsWithFormstrait。 - 添加用于配置表格的
table()方法,。添加表格列字段、过滤器和 Action。 - 确保在表格中配置了用于获取行数据的基础查询。比如,如果要从
Product模型中罗列产品,你可能需要返回Product::query()。
<?php
namespace App\Livewire;
use App\Models\Post;
use App\Models\Shop\Product;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Contracts\View\View;
use Livewire\Component;
class ListProducts extends Component implements HasForms, HasTable
{
use InteractsWithTable;
use InteractsWithForms;
public function table(Table $table): Table
{
return $table
->query(Product::query())
->columns([
TextColumn::make('name'),
])
->filters([
// ...
])
->actions([
// ...
])
->bulkActions([
// ...
]);
}
public function render(): View
{
return view('list-products');
}
}