php - 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>
解决方案
<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,这会给你现在的冲突
推荐阅读
- python-3.x - 程序输入学生的详细信息,学生学习的模块,考试成绩,计算gpa并使用python将结果写入txt文件。
- r - 在 x 轴上绘制经过的天数
- reactjs - 如何配置 Office-js excel react 插件以使用 react-router-dom 或替代解决方案?
- android - 如何在android studio中删除标签
- android - 如何知道用哪种语言编写的应用程序
- database - 在 Oracle 12 中创建数据库快照
- amazon-web-services - 如何在 AWS 中找到有关现有资源的正确 ID 以便导入 Terraform 资源?
- tcl - 如何解释 openOCD 手册中的 tcl 命令
- c - 为什么在函数中声明字符串参数需要C中的指针?
- sql - 使用 date_trunc 自定义一周的范围