You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Livewire 3中实现组件内按钮删除自身的方法咨询

Livewire 3 实现子组件删除自身的方法

步骤1:修改子组件(InvoiceRow)传递索引

在InvoiceRow组件中,需要将自身的index参数通过事件传递给父组件,让父组件明确要删除哪一行:

Blade 视图(保持不变)

<div class="col-md-1">
    <button wire:click="confirmDelete" class="btn btn-danger"><i class="fa fa-trash"></i> Delete</button>
</div>

PHP 逻辑

public int $index;

public function confirmDelete()
{
    // 触发deleteRow事件并携带当前行的index
    $this->dispatch('deleteRow', index: $this->index);
}

步骤2:修改父组件(CreateInvoice)的逻辑

父组件需要改用数组维护行数据(替代原有的$rowCount),这样可以灵活删除任意位置的行,同时避免DOM索引冲突:

1. 定义行数组变量

在CreateInvoice类中声明用于存储行数据的数组:

public array $rows = [];

2. 修改添加行的方法

将原来的increaseRowCount方法改为向数组中添加元素:

public function increaseRowCount()
{
    $this->rows[] = []; // 可根据需求存储行的实际数据,此处先占位
}

3. 实现删除行的方法

修正事件监听注解,并编写删除逻辑:

#[On('deleteRow')]
public function deleteRow(int $index)
{
    // 删除指定索引的行
    unset($this->rows[$index]);
    // 重新索引数组,避免索引断层导致循环异常
    $this->rows = array_values($this->rows);
}

4. 修改Blade循环逻辑

将基于range的循环改为遍历行数组,确保每个子组件的key唯一且对应正确索引:

<div class="mt-5">
    @foreach ($rows as $index => $row)
        @livewire('invoice-row', ['index' => $index], key($index))
    @endforeach
    <br>
    <button type="button" wire:click="increaseRowCount" name="addRow" class="btn btn-success float-right">Add New Row</button>
</div>

关键说明

  • 弃用$rowCount的原因:仅通过$rowCount控制行数只能删除最后一行,无法定位具体子组件,还会导致循环索引与组件key混乱,引发Livewire DOM更新异常。
  • 组件key的作用:使用循环的$index作为子组件的key,确保Livewire能准确识别每个组件,删除时正确移除对应DOM元素。

内容的提问来源于stack exchange,提问作者Om WT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:03:26