问题描述
当结合 Laravel-Livewire 和动态更改呈现在 html 表中的数据时,我一直在为 foreach
刀片指令苦苦挣扎。
具体场景:
听起来很简单,但我无法让它正常工作。
<?PHP
namespace App\Http\Livewire;
use Livewire\Component;
class UnreconciledServices extends Component
{
public $services;
public function render()
{
return view('livewire.unreconciled-services');
}
//
// receives an invoice number and changes the "reconciled" value for the $aaaServices record to true
//
public function test($a)
{
}
}
这非常简单 - 有一个名为“test”的函数接受一个变量(该函数什么都不做),还有一个名为 $services 的记录集合,它是从父级传入的。
刀片文件如下:
<div>
<table style="width:100%">
<thead>
<tr>
<th width="5%">
</th>
<th>
Service Date
</th>
<th>
Call #
</th>
<th>
Payment
</th>
</tr>
</thead>
<tbody>
@foreach ($services as $service)
{{-- <span wire:key="{{$service->invoice_number}}"> --}}
{{-- @if ($service->reconciled == false) --}}
<tr id="{{$service->invoice_number}}" class="text-center" style="{{ $service->reconciled == 1 ? 'display:none' : 'show'}}">
<td>
{{-- <input class="m-2" type="checkBox"> --}}
{{-- <span class="m-2"><i class="far fa-trash-alt text-red-500"></i></span> --}}
<span wire:key="{{$service->invoice_number}}" wire:click="test('{{$service->invoice_number}}')" class="m-2 cursor-pointer"><i class="lm-2 rm-2 fas fa-plus text-green-500"></i></span>
</td>
<td>
{{$service->invoice_date}}
</td>
<td>
{{$service->call_number}}
</td>
<td>
{{$service->service_price}}
</td>
</tr>
{{-- @endif --}}
{{-- </span> --}}
@endforeach
</tbody>
</table>
</div>
这是一个有 4 列的简单表格。第一个是可点击的图标,其他三个是数据。仅当“已协调”布尔值为 0 时,行才应可见。
最初呈现时,会显示相应的记录(有 2 个符合条件,177 个不符合条件)。但是,一旦我单击该图标——即使它链接到的函数的实际内容为零——所有记录都突然可见除了我刚刚隐藏的那个。
查看点击图标时的html变化,标签从
<tr id="21031251674" class="text-center" style="display:none">
到
<tr id="21031253205" class="text-center" style="show">
。
我尝试过使用 livewire 键,但我不确定这会如何影响功能,因为我不是渲染组件,而是数据驱动的 html。
肯定有人遇到过这种情况并克服了。请为我指明正确的方向。
解决方法
抱歉耽搁了。这整个线程应该作为骨头删除。但是写得很认真...
当一切都说完后,我不清楚 b/w 基于 html / ajax 的方法(例如 livewire)和更多基于 javascript 的方法(例如 Vue)之间的区别。在我尝试使用框架时,我期待着框架中不存在的功能。
为了解决这个问题,我转向将单独的行项目作为组件本身,使用 emit
在组件之间进行通信并调整后端数据源。
一旦我接受了 html/ajax 方法并停止尝试强制/期望 javascript 功能和 dom 操作,那么一切都很好。只是和我熟悉的心态不同,我花了一些时间来转过弯。