Laravel Livewire - 如何强制子组件刷新
Laravel Livewire - How to force child component refresh
我想在更新父组件时刷新子组件,并且只有该组件的子组件应该更新,因为我想在页面的其他地方重用该子组件。组件结构如下。
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()
方法更改时,我希望 UserShowEmail
中的 $user
属性会相应更改。通过阅读the docs,Livewire 似乎无法自动刷新子组件。
我想知道是否有解决方法,或者允许我在父组件更改时刷新子组件的方法。
谢谢!
如果您不介意更新整个子组件,这将是一种方法:
There's a trick that always work for me when I want to make a child
Livewire component "reactive". In your parent livewire component you
use 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 now
will always be updated when the parent is updated.
在你的父组件中:
<div>
...
<div>
Name: {{ $user->name }}
<livewire:user-show-email key="{{ now() }}" :user="$user" />
</div>
</div>
我想在更新父组件时刷新子组件,并且只有该组件的子组件应该更新,因为我想在页面的其他地方重用该子组件。组件结构如下。
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()
方法更改时,我希望 UserShowEmail
中的 $user
属性会相应更改。通过阅读the docs,Livewire 似乎无法自动刷新子组件。
我想知道是否有解决方法,或者允许我在父组件更改时刷新子组件的方法。
谢谢!
如果您不介意更新整个子组件,这将是一种方法:
There's a trick that always work for me when I want to make a child Livewire component "reactive". In your parent livewire component you use 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 now will always be updated when the parent is updated.
在你的父组件中:
<div>
...
<div>
Name: {{ $user->name }}
<livewire:user-show-email key="{{ now() }}" :user="$user" />
</div>
</div>