未使用 Livewire 删除表格行

问题描述 投票:0回答:1

我创建了一个动态行,我想删除该行,但仅删除该行中的数据,并且不更新输入字段。我在此使用 Livewire 来创建行和删除行。 输入字段的 UI 未删除。

我已经尝试过,但这只是从行中删除了数据。

这是按钮代码:

public function removeRow($index){
   array_splice($this->createChallanRequest['order_details'], $index, 1);
}
 
php arrays laravel laravel-livewire unset
1个回答
0
投票

我假设您正在使用循环来显示行。为了让 Livewire 了解要在 DOM 中更新哪些行,您需要为每行提供唯一的 wire:key 属性:

@foreach ($users as $user)
    <div wire:key="user-{{ $user->id }}">
        User name: {{ $user->name }}
    </div>
@endforeach

在此示例中,我使用带有前缀的记录 ID(如果同一页面上有多个列表,则很有用)作为 wire:key

如果您显示数组并且行中没有唯一的 id,则可以使用数组索引,但必须确保它不会被回收(无论是在更改行时还是在对行进行分页时) :

@foreach ($order_details as $key => $order_detail)

    <div wire:key="prefix-{{ $key }}">
        .....
        
        <button wire:click="removeRow({{ $key }})">
           DELETE
        </button>
    
    </div>

@endforeach

因此,当您删除一行时,您不能使用 splice() 来实现此目的,因为它会压缩索引。您可以使用简单的 unset() 来删除行,但保留索引不变:

public function removeRow($index){ 
   // I assume that  $this->createChallanRequest  is a property
   unset ($this->createChallanRequest['order_details'][$index]);
}
© www.soinside.com 2019 - 2024. All rights reserved.