Events
Component communication via dispatching and listening to events.
Dispatching Events
Components can emit events that other components can listen to.
PHP
// Broadcast to all components
$this->dispatch('item-saved', ['id' => $item->id]);
// Dispatch only to this component
$this->dispatchSelf('refresh-data');
// Dispatch to a specific component
$this->dispatchTo('cart', 'item-added', ['product' => $product]);
Listening to Events
Two ways to listen for events: the $listeners property or the #[On] attribute.
$listeners property
protected array $listeners = [
'item-saved' => 'handleSaved',
'refresh' => '$refresh',
];
public function handleSaved($data)
{
// $data['id'] available
}
#[On] attribute
use LiVue\Attributes\On;
#[On('item-saved')]
public function handleSaved($data)
{
// Handle event
}
#[On('refresh')]
public function refresh()
{
// Refresh component
}
Client-Side Events
Dispatch events directly from JavaScript without a server round-trip.
<!-- In template -->
<button @click="livue.dispatch('modal-opened', { id: 123 })">
Open Modal
</button>
<!-- Global dispatch -->
<script>
LiVue.dispatch('theme-changed', { dark: true });
</script>
Dispatch Modes
| Method | Target | Use Case |
|---|---|---|
| dispatch() | All components | Global notifications, state sync |
| dispatchSelf() | Same component | Internal state updates |
| dispatchTo() | Specific component | Parent-child communication |
Example: Modal Communication
Parent (emits)
public function openModal()
{
$this->dispatchTo(
'modal',
'show',
['title' => 'Confirm']
);
}
Modal (listens)
public bool $visible = false;
public string $title = '';
#[On('show')]
public function show($data)
{
$this->title = $data['title'];
$this->visible = true;
}