gpt4 book ai didi

Laravel Livewire - 如何强制子组件刷新

转载 作者:行者123 更新时间:2023-12-03 21:44:36 25 4
gpt4 key购买 nike

我想在更新父组件时刷新子组件,并且只有该组件的子组件应该更新,因为我想在页面的其他地方重用子组件。组件结构如下。UserShow.php

class UserShow extends Component
{
public User $user;
public int $userId;

public function mount() {
$this->user = User::first();
}

public function updatedUserId() {
$this->user = User::find($this->userId);
}

public function render() {
return view('livewire.user-show');
}
}
<div>
<select wire:model="userId">
<option value="1">Matteo</option>
<option value="2">Giulia</option>
<option value="3">Mattia</option>
</select>

<div>
Name: {{ $user->name }}
@livewire('user-show-email', ['user' => $user])
</div>
</div>
UserShowEmail.php
class UserShowEmail extends Component
{
/** @var User */
public $user;

public function render() {
return view('livewire.user-show-email');
}
}
<div>
Email: {{ $user->email }}
</div>
当用户在 UserShow通过 updatedUserId() 更改方法,我想要 $user Prop 在 UserShowEmail会相应改变。通过阅读 the docs Livewire 似乎无法自动刷新子组件。
我想知道是否有解决方法,或者允许我在父组件更改时刷新子组件。
谢谢!

最佳答案

如果您不介意更新整个子组件,这将是一种方法:

There's a trick that always work for me when I want to make a childLivewire component "reactive". In your parent livewire component youuse a timestamp for the key attribute:

<livewire:child-component key="{{ now() }}" :my-prop="$myModel" />

The tricky part is the now() function in key prop. This component nowwill always be updated when the parent is updated.


在您的父组件中:
<div>
...

<div>
Name: {{ $user->name }}
<livewire:user-show-email key="{{ now() }}" :user="$user" />
</div>
</div>
您可以阅读更多相关信息 herehere .

关于Laravel Livewire - 如何强制子组件刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65392402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com