Laravel Livewire按数据库选中项单位条件动态显隐输入框的方法
实现方案
首先修正原有代码的两处基础错误:
- 原有Blade中
@if ($item->etape = 'Réception')用了单等号赋值,不是相等判断,会导致所有参数的etape被强制赋值为Réception,下拉选项显示完全错误 - 原有判断逻辑写在
<option>标签内部,不匹配的参数会渲染为空的无效option标签
1. Livewire组件端逻辑配置
在对应Livewire组件类中新增以下代码:
- 新增公开属性存储每个索引对应的选中参数单位,适配多行动态场景:
public array $currentUnit = []; - 完善已有的
showUnite方法,根据选中值读取对应单位:
public function showUnite(int $index) { $paramId = $this->production_parametre_fixes_id[$index] ?? 0; // 选中为空时清空对应单位缓存 if (!$paramId) { unset($this->currentUnit[$index]); return; } // 直接从已有参数列表匹配,避免重复查询数据库 $selectedParam = collect($this->list_parametres)->firstWhere('id', $paramId); $this->currentUnit[$index] = $selectedParam?->unite; }
- 若为编辑场景(页面加载时已有选中参数),在
mount方法中补充初始化逻辑,避免首次加载时输入框不显示:
public function mount() { // 预加载已有选中项的单位判断 foreach ($this->production_parametre_fixes_id ?? [] as $index => $paramId) { if ($paramId) { $this->showUnite($index); } } }
2. Blade模板改造
调整原有模板的判断逻辑和条件渲染:
<select class="form-control" wire:model.defer="production_parametre_fixes_id.0" wire:change="showUnite(0)"> <option value="0">Choisir</option> @foreach ($list_parametres as $item) {{-- 修正判断为双等号相等校验,仅匹配的参数输出option --}} @if ($item->etape == 'Réception') <option value="{{ $item->id }}"> {{ $item->matiere }} | {{ $item->unite }} </option> @endif @endforeach </select> {{-- 仅选中单位为KG或l时显示数量输入框 --}} @if(in_array($currentUnit[0] ?? '', ['KG', 'l'])) <input type="text" class="form-control" placeholder=" " wire:model.defer="qte_materiel.0"/> @endif {{-- 仅选中单位为h时显示时间输入框 --}} @if(($currentUnit[0] ?? '') === 'h') <input type="time" class="form-control" placeholder=" " wire:model.defer="debut.0"/> @endif
3. 注意事项
- 若数据库中
unite字段存在大小写不统一的情况,判断时统一转换字符大小写即可,比如mb_strtolower($currentUnit[0] ?? '') === 'kg',避免判断失效 - 如果需要选中后立刻响应(不等其他表单提交),可以将select的
wire:model.defer改为wire:model.live,避免defer延迟导致单位值不更新 - 这套逻辑完全适配后续动态新增多参数行的场景,新增行时传入对应索引即可直接复用
内容的提问来源于stack exchange,提问作者Hajat Raoui
相关产品推荐
相关产品推荐

