如何解决如何使用livewire更新表中的子组件?
在更改子级父级时可以嵌套组件有问题,并且可以,但是当我通过使用条形码在CartItem中添加相同产品时,子级组件中的数量未更改 这是我的父组件,包括表格 parent.blade.php >>>
<table class="table mb-0">
<thead>
<tr>
<th scope="col">product</th>
<th>price</th>
<th>quantity</th>
</tr>
</thead>
<tbody>
@foreach ($cartItems as $item)
<tr>
<td>{{$item['name']}}</td>
<td>{{Cart::session(auth()->id())->get($item['id'])->getPriceSum()}}</td>
<td>
<livewire:child :item="$item" wire:key="$item['id']"/>
</td>
</tr>
@endforeach
</tbody>
</table>
和这个id parent.php
class Parent extends Component
{
public $service = null;
public $cartItems = [];
protected $listeners = ['cartUpdated' => 'onCartUpdate'];
public function mount()
{
$this->cartItems = \Cart::session(auth()->id())->getContent()->toArray();
}
public function onCartUpdate()
{
$this->mount();
}
public function render()
{
$this->mount();
return view('livewire.parent');
}
}
<td>
中的子组件仅带有livewire:model
的输入
<div>
<input type="number" wire:model="quantity" wire:change="updateCart"><span class="col-9"></span>
</div>
我的Child.php
class Child extends Component
{
public $item;
public $quantity;
public function mount($item)
{
$this->item = $item;
$this->quantity = $item['quantity'];
}
public function updateCart()
{
\Cart::session(auth()->id())->update($this->item['id'],[
'quantity' => array(
'relative' => false,'value' => $this->quantity,),]);
$this->emit('cartUpdated');
}
public function render()
{
return view('livewire.child');
}
}
我认为这会返回孩子的mount()
方法。我可以每次更新数量吗?
解决方法
代替调用onCartUpdate
方法。尝试在$refresh
中使用$listeners
:
protected $listeners = ['cartUpdated' => '$refresh'];
,
您没有正确利用数据绑定。您无需添加wire:change
,因为您已经拥有wire:model
-您只需侦听对该属性的更改即可。
更好的是,仅使用一个属性$item
并从中访问数量。
<div>
<input type="number" wire:model="item.quantity" /> <span class="col-9"></span>
</div>
然后使用“魔术”方法updatedItemQuantity()
来监听对quantity
属性上的$item
属性的更新。
class Child extends Component
{
public $item;
protected $rules = [
'item.quantity' => 'required|numeric|min:0',];
public function mount($item)
{
$this->item = $item;
}
public function updatedItemQuantity($quantity)
{
\Cart::session(auth()->id())->update($this->item['id'],[
'quantity' => array(
'relative' => false,'value' => $quantity,),]);
$this->emit('cartUpdated');
}
public function render()
{
return view('livewire.child');
}
}
现在在您的父母中,您只需使用“魔术”事件$refresh
,
class Parent extends Component
{
public $service = null;
public $cartItems = [];
protected $listeners = ['cartUpdated' => '$refresh'];
public function mount()
{
$this->cartItems = \Cart::session(auth()->id())->getContent()->toArray();
}
public function render()
{
return view('livewire.parent');
}
}
,
有一种方法可以使子组件具有反应性。只需使用now()
或随机数作为密钥,如下所示:
<livewire:child :item="$item" key="{{now()}}"/>
很高兴看到这个tricky way对我有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。