MyLivewireComponent.php
<?php
namespace AppLivewire;
use LivewireComponent;
use AppModelsPerson;
class MyLivewireComponent extends Component {
public $persons;
public function mount() {
$this->persons = Person::all();
}
public function render() {
return view('livewire.my-livewire-component');
}
}
?>
When the browser’s window got focused (focus
event), I just want to update the contents and value of the $persons
variable by re-executing the statement:
$this->persons = Person::all();
So that it would get the new comprehensive list if ever there were additions to that collection.
This is because on my Blade…
my-livewire-component.blade.php
<select>
@foreach($persons as $person)
<option value="{{ $person->id }}">{{ $person->name }}</option>
@endforeach
</select>
This would ensure that the dropdown list is always updated once the user is back to the web application.
Which brings me back to my question. How to update a variable of the Livewire component class when window focus event happens?
2
Answers
I was able to do this by...
MyLivewireComponent.php
my-livewire-component.blade.php
Versions
v10.35.0
v3.2.6
If you are using AlpineJS you could use the x-on method. Using this handle you can fire events to execute Livewire methods that updates the Person list.
Example:
Livewire events
AlpineJS x-on directive
AlpineJS $dispatch magic