首页 > 解决方案 > Laravel/Livewire 嵌套输入字段在页面加载时消失

问题描述

我是 Livewire/Jetstream 的新手,我正在尝试制作一个小库存应用程序来尝试一下。在下面的示例中,我试图在表上显示数据库中的库存项目,并且能够在不进入编辑页面的情况下从表中更新库存名称和数量。

我有一个嵌套的 foreach,当我呈现页面时,循环中的输入字段显示值然后消失,但值在 HTML 中正确显示。任何帮助,将不胜感激!

缺少字段

**Show Inventory**

namespace App\Http\Livewire;
use App\Models\Inventory;
use Livewire\Component;

class ShowInventory extends Component
{
    
    public $inventories;

    public function mount() 
    {
        $this->inventories = Inventory::orderBy('name')->get();
    }

    public function render()
    {
        return view('livewire.show-inventory');
    }

    public function name()
    {
        $this->name = $name;
    }

    public function update($id)
    {
        $data = $this->validate([
            'name' => 'required',
            'available_on_hand' => 'required',
        ]);

        $this->item_id = $id;

        $item = Inventory::find($this->item_id);

        $item->update([
            'name' => $this->name,
            'available_on_hand' => $this->available_on_hand,
        ]);

    }
}

**Show Item**

namespace App\Http\Livewire;
use App\Models\Inventory;
use Livewire\Component;

class ShowItem extends Component
{

    public $inventory;

    public function mount(Inventory $inventory)
    {
        $this->inventory = $inventory;
    }

    public function render()
    {
        return view('livewire.show-item');
    }
}
**Parent Blade**

<table class="table-auto">
 <thead>
  <tr>
   <th>Name</th>
   <th>Quantity</th>
   <th></th>
   <th>View</th>
  </tr>
 </thead>
 <tbody>
  @foreach($inventories as $inventory)
   @livewire('show-item', ['inventory' => $inventory], key($inventory->id))
  @endforeach
 </tbody>
</table>
**Nested Blade**

<form wire:submit.prevent="update({{ $inventory->id }})">
    <tr>
        <td><input type="input" wire:model="name" value="{{$inventory->name}}" /></td>
        <td><input type="input" wire:model="available_on_hand" value="{{$inventory->available_on_hand}}" /></td>
        <td><button type="submit">Save</button></td>
        <td>View</td>
    </tr>
</form>

标签: phplaravellaravel-livewire

解决方案



<form wire:submit.prevent="update({{ $inventory->id }})">
    <tr>
        <td><input type="input" wire:model="name"/></td>
        <td><input type="input" wire:model="available_on_hand"/></td>
        <td><button type="submit">Save</button></td>
        <td>View</td>
    </tr>
</form>

在组件中

public $name, $available_on_hand;

//....

public function getModel($modelID)
{
   $model = Inventory::find($modelID);
   $this->name = $model->name;
   $this->available_on_hand = $model->available_on_hand;
}

如您所见,始终调用 getModel 方法,它将模型的当前值绑定到您的属性,您也可以编辑它们并保存它。你不能同时使用 value 属性和 wire:model,这会给你现在的冲突


推荐阅读