Filament 4含嵌套Repeater的表单加载渲染缓慢问题求助
Filament 4嵌套Repeater表单性能优化方案
针对你三层嵌套Repeater表单的性能问题,以下是具体优化建议:
1. 限制Repeater的默认项与最大项数
过多的预渲染空项会导致DOM节点爆炸,直接拖慢渲染速度。给每个Repeater设置合理的默认显示数量和最大可添加数量:
Repeater::make('sections') ->defaultItems(1) // 默认只显示1个空项 ->maxItems(5) // 根据业务需求限制最大数量 ->schema([ TextInput::make('title'), Repeater::make('items') ->defaultItems(1) ->maxItems(10) ->schema([ TextInput::make('name'), Repeater::make('options') ->defaultItems(1) ->maxItems(5) ->schema([ TextInput::make('label'), TextInput::make('value'), ]), ]), ])
2. 启用Repeater延迟加载
Filament 4支持lazy()方法,只在用户点击添加按钮时才渲染新项,避免预渲染大量空DOM:
Repeater::make('sections') ->lazy() ->schema([ Repeater::make('items') ->lazy() ->schema([ Repeater::make('options') ->lazy() ->schema([/*...*/]), ]), ])
3. 优化Select组件性能
如果getChecklistIncidentCategoryOptions返回的选项数量极大,会直接拖慢Select渲染:
- 开启搜索功能,减少一次性渲染的选项数
- 选项过多时改用异步加载
Select::make('category_id') ->options(fn () => static::getChecklistIncidentCategoryOptions(true)) ->searchable() // 开启搜索过滤 ->async() // 异步加载选项(选项数量大时建议用) ->columnSpanFull() ->native(false) ->multiple(),
同时给选项获取方法加缓存,避免重复查询:
public static function getChecklistIncidentCategoryOptions(bool $someParam) { return Cache::remember('incident_category_options_' . $someParam, 3600, function () use ($someParam) { // 原有的选项获取逻辑,比如数据库查询 return IncidentCategory::query()->pluck('name', 'id')->toArray(); }); }
4. 减少不必要的交互与渲染
- 关闭Repeater的添加/删除动画,大量操作时动画会严重卡顿:
Repeater::make('sections') ->disableAnimation() ->schema([/*...*/])
- 让嵌套Repeater默认折叠,减少初始渲染的DOM数量:
Repeater::make('items') ->collapsible() ->collapsed() // 默认折叠 ->schema([/*...*/])
5. 基础环境优化
- 确保使用最新版Filament 4,官方会持续修复性能相关bug
- 检查页面是否存在第三方脚本(如统计、广告)占用资源,暂时禁用测试性能变化
内容的提问来源于stack exchange,提问作者Hedi tropex Souaied
相关产品推荐
相关产品推荐

