イベント
Livewireは、ページ上の異なるコンポーネント間で通信するために使用できる堅牢なイベントシステムを提供しています。内部的にはブラウザイベントを使用しているため、Livewireのイベントシステムを使用して、AlpineコンポーネントやプレーンなバニラJavaScriptとも通信可能です。Livewire offers a robust event system that you can use to communicate between different components on the page. Because it uses browser events under the hood, you can also use Livewire's event system to communicate with Alpine components or even plain, vanilla JavaScript.
イベントをトリガーするには、コンポーネント内の任意の場所でdispatch()
メソッドを使用し、ページ上の他のコンポーネントからそのイベントをリッスンします。To trigger an event, you may use the dispatch()
method from anywhere inside your component and listen for that event from any other component on the page.
イベントの発行Dispatching events
Livewireコンポーネントからイベントを発行するには、dispatch()
メソッドを呼び出し、イベント名とイベントとともに送信する追加データを渡します。To dispatch an event from a Livewire component, you can call the dispatch()
method, passing it the event name and any additional data you want to send along with the event.
以下は、CreatePost
コンポーネントからpost-created
イベントを発行する例です。Below is an example of dispatching a post-created
event from a CreatePost
component:
use Livewire\Component;
class CreatePost extends Component
{
public function save()
{
// ...
$this->dispatch('post-created'); // [tl! highlight]
}
}
この例では、dispatch()
メソッドを呼び出すと、post-created
イベントが発行され、このイベントをリッスンしているページ上の他のすべてのコンポーネントへ通知します。In this example, when the dispatch()
method is called, the post-created
event will be dispatched, and every other component on the page that is listening for this event will be notified.
イベントと一緒に追加のデータを渡すには、データをdispatch()
メソッドの 第2パラメータとして渡します。You can pass additional data with the event by passing the data as the second parameter to the dispatch()
method:
$this->dispatch('post-created', title: $post->title);
イベントのリッスンListening for events
Livewireコンポーネントでイベントをリッスンするには、指定イベントが発行されたときに呼び出すメソッドの上に#[On]
属性を追加します。To listen for an event in a Livewire component, add the #[On]
attribute above the method you want to be called when a given event is dispatched:
Warning! 属性クラスを必ずインポートしてください: すべての属性クラスを必ずインポートしてください。たとえば、以下の
#[On()]
属性には、以下のuse Livewire\Attributes\On;
のインポートが必要です。[!warning] Make sure you import attribute classes Make sure you import any attribute classes. For example, the below#[On()]
attributes requires the following importuse Livewire\Attributes\On;
.
use Livewire\Component;
use Livewire\Attributes\On; // [tl! highlight]
class Dashboard extends Component
{
#[On('post-created')] // [tl! highlight]
public function updatePostList($title)
{
// ...
}
}
これで、CreatePost
からpost-created
イベントを発行すると、ネットワークリクエストをトリガーし、updatePostList()
アクションが呼び出されます。Now, when the post-created
event is dispatched from CreatePost
, a network request will be triggered and the updatePostList()
action will be invoked.
ご覧のとおり、イベントとともに送信した追加データは、最初の引数としてアクションへ渡されます。As you can see, additional data sent with the event will be provided to the action as its first argument.
動的なイベント名のリッスンListening for dynamic event names
場合によっては、コンポーネントからのデータを使用して、実行時にイベントリスナ名を動的に生成したい場合があります。Occasionally, you may want to dynamically generate event listener names at run-time using data from your component.
たとえば、イベントリスナの範囲を特定のEloquentモデルに限定したい場合は、次のように発行時にモデルのIDをイベント名へ追加できます。For example, if you wanted to scope an event listener to a specific Eloquent model, you could append the model's ID to the event name when dispatching like so:
use Livewire\Component;
class UpdatePost extends Component
{
public function update()
{
// ...
$this->dispatch("post-updated.{$post->id}"); // [tl! highlight]
}
}
次に、その特定のモデルをリッスンします。And then listen for that specific model:
use Livewire\Component;
use App\Models\Post;
use Livewire\Attributes\On; // [tl! highlight]
class ShowPost extends Component
{
public Post $post;
#[On('post-updated.{post.id}')] // [tl! highlight]
public function refreshPost()
{
// ...
}
}
上記の$post
モデルのIDが3
の場合、refreshPost()
メソッドはpost-updated.3
という名前のイベントによってのみトリガーされます。If the above $post
model had an ID of 3
, the refreshPost()
method would only be triggered by an event named: post-updated.3
.
特定の子コンポーネントからのイベントのリッスンListening for events from specific child components
Livewireでは、以下のようにBladeテンプレート内の個々の子コンポーネントでイベントを直接リッスンできます。Livewire allows you to listen for events directly on individual child components in your Blade template like so:
<div>
<livewire:edit-post @saved="$refresh">
<!-- ... -->
</div>
上記のシナリオで、edit-post
子コンポーネントがsaved
イベントを発行すると、親の$refresh
が呼び出され、親がリフレッシュされます。In the above scenario, if the edit-post
child component dispatches a saved
event, the parent's $refresh
will be called and the parent will be refreshed.
$refresh
を渡す代わりに、wire:click
などへ渡すのと同じように、任意のメソッドを渡すことができます。モーダルダイアログを閉じるような、close()
メソッドを呼び出す例を以下に紹介します。Instead of passing $refresh
, you can pass any method you normally would to something like wire:click
. Here's an example of calling a close()
method that might do something like close a modal dialog:
<livewire:edit-post @saved="close">
たとえば、$this->dispatch('saved', postId: 1)
のように、子がリクエストとともにパラメータを発行した場合、以下の構文を使用して、そうした値を親メソッドへ転送できます。If the child dispatched parameters along with the request, for example $this->dispatch('saved', postId: 1)
, you can forward those values to the parent method using the following syntax:
<livewire:edit-post @saved="close($event.detail.postId)">
JavaScriptを使用したイベントの操作Using JavaScript to interact with events
Livewireのイベントシステムは、アプリケーション内のJavaScriptから操作すると、はるかに強力になります。これにより、アプリ内の他のJavaScriptが、ページ上のLivewireコンポーネントと通信できるようになります。Livewire's event system becomes much more powerful when you interact with it from JavaScript inside your application. This unlocks the ability for any other JavaScript in your app to communicate with Livewire components on the page.
コンポーネントスクリプト内でのイベントのリッスンListening for events inside component scripts
次のように、@script
ディレクティブからコンポーネントのテンプレート内で post-created
イベントを簡単にリッスンできます。You can easily listen for the post-created
event inside your component's template from a @script
directive like so:
@script
<script>
$wire.on('post-created', () => {
//
});
</script>
@endscript
上記のコードスニペットは、登録しているコンポーネントからの post-created
をリッスンします。コンポーネントがページに存在しなくなった場合、イベントリスナはトリガーされなくなります。The above snippet would listen for the post-created
from the component it's registered within. If the component is no longer on the page, the event listener will no longer be triggered.
LivewireコンポーネントでのJavaScriptの使用の詳細はこちら ←
コンポーネントスクリプトからのイベントの発行Dispatching events from component scripts
さらに、次のようにコンポーネントの@script
内からもイベントを発行できます。Additionally, you can dispatch events from within a component's @script
like so:
@script
<script>
$wire.dispatch('post-created');
</script>
@endscript
上記の@script
が実行されると、post-created
イベントは、それを定義しているコンポーネントにディスパッチされます。When the above @script
is run, the post-created
event will be dispatched to the component it's defined within.
スクリプトが存在するコンポーネントにのみイベントを発行し、ページ上の他のコンポーネントには発行しないようにするには (イベントが「バブリング」するのを防ぐため)、dispatchSelf()
を使用します。To dispatch the event only to the component where the script resides and not other components on the page (preventing the event from "bubbling" up), you can use dispatchSelf()
:
$wire.dispatchSelf('post-created');
イベントに追加のパラメータを渡すには、dispatch()
の第2引数としてオブジェクトを渡します。You can pass any additional parameters to the event by passing an object as a second argument to dispatch()
:
@script
<script>
$wire.dispatch('post-created', { refreshPosts: true });
</script>
@endscript
これで、Livewireクラスと他のJavaScriptイベントリスナの両方から、これらのイベントパラメータへアクセスできるようになりました。You can now access those event parameters from both your Livewire class and also other JavaScript event listeners.
Livewireクラス内でrefreshPosts
パラメータを受信する例を以下に示します。Here's an example of receiving the refreshPosts
parameter within a Livewire class:
use Livewire\Attributes\On;
// ...
#[On('post-created')]
public function handleNewPost($refreshPosts = false)
{
//
}
JavaScriptイベントリスナから、イベントのdetail
プロパティを通じて、 refreshPosts
パラメータへアクセスすることもできます。You can also access the refreshPosts
parameter from a JavaScript event listener from the event's detail
property:
@script
<script>
$wire.on('post-created', (event) => {
let refreshPosts = event.detail.refreshPosts
// ...
});
</script>
@endscript
Livewire コンポーネントでの JavaScript の使用の詳細はこちら ←
グローバルJavaScriptからのLivewireイベントのリッスンListening for Livewire events from global JavaScript
もしくは、Livewire.on
を使用して、アプリケーション内の任意のスクリプトからLivewireイベントをグローバルにリッスンできます。Alternatively, you can listen for Livewire events globally using Livewire.on
from any script in your application:
<script>
document.addEventListener('livewire:init', () => {
Livewire.on('post-created', (event) => {
//
});
});
</script>
上記のコードスニペットは、ページ上の任意のコンポーネントが発行したpost-created
イベントをリッスンします。The above snippet would listen for the post-created
event dispatched from any component on the page.
何らかの理由でこのイベントリスナを削除したい場合は、返されたcleanup
関数を使用して削除できます。If you wish to remove this event listener for any reason, you can do so using the returned cleanup
function:
<script>
document.addEventListener('livewire:init', () => {
let cleanup = Livewire.on('post-created', (event) => {
//
});
// "cleanup()"を呼び出すと、上記のイベントリスナの登録を解除します
cleanup();
});
</script>
Alpine でのイベントEvents in Alpine
Livewire イベントは内部的にはプレーンなブラウザイベントであるため、Alpine を使用してそれらをリッスンしたり、発行したりすることもできます。Because Livewire events are plain browser events under the hood, you can use Alpine to listen for them or even dispatch them.
Alpine での Livewire イベントのリッスンListening for Livewire events in Alpine
たとえば、Alpineを使用してpost-created
イベントを簡単にリッスンできます。For example, we may easily listen for the post-created
event using Alpine:
<div x-on:post-created="..."></div>
上記のコードスニペットは、x-on
ディレクティブを割り当てているHTML要素の子である、Livewireコンポーネントからのpost-created
イベントをリッスンします。The above snippet would listen for the post-created
event from any Livewire components that are children of the HTML element that the x-on
directive is assigned to.
ページ上の任意のLivewireコンポーネントからのイベントをリッスンするには、リスナに.window
を追加できます。To listen for the event from any Livewire component on the page, you can add .window
to the listener:
<div x-on:post-created.window="..."></div>
イベントとともに送信された追加データへアクセスする場合は、$event.detail
を使用してアクセスします。If you want to access additional data that was sent with the event, you can do so using $event.detail
:
<div x-on:post-created="notify('New post: ' + $event.detail.title)"></div>
Alpineのドキュメントには、イベントのリッスンに関する詳細情報が記載されています。The Alpine documentation provides further information on listening for events[https://alpinejs.dev/directives/on].
AlpineからのLivewireイベントの発行Dispatching Livewire events from Alpine
Alpineから発行したイベントをLivewireコンポーネントは傍受する能力があります。Any event dispatched from Alpine is capable of being intercepted by a Livewire component.
例を見てみると、Alpineからpost-created
イベントを簡単に発行できます。For example, we may easily dispatch the post-created
event from Alpine:
<button @click="$dispatch('post-created')">...</button>
Livewireのdispatch()
メソッドと同様に、データをメソッドの第2引数として渡せば、イベントと一緒に追加のデータを渡せます。Like Livewire's dispatch()
method, you can pass additional data along with the event by passing the data as the second parameter to the method:
<button @click="$dispatch('post-created', { title: 'Post Title' })">...</button>
Alpineを使用したイベントの発行の詳細については、Alpineドキュメントを参照してください。To learn more about dispatching events using Alpine, consult the Alpine documentation[https://alpinejs.dev/magics/dispatch].
Tip: イベントが必要ない場合があります: イベントを使用して子から親の動作を呼び出す場合は、代わりにBladeテンプレートで
$parent
を使用してアクションを子から直接呼び出すことができます。例:[!tip] You might not need events If you are using events to call behavior on a parent from a child, you can instead call the action directly from the child using$parent
in your Blade template. For example:<button wire:click="$parent.showCreatePostForm()">Create Post</button>
$parentの詳細はこちら。Learn more about $parent[/docs/nesting#directly-accessing-the-parent-from-the-child].
別のコンポーネントへの直接発行Dispatching directly to another component
イベントを使用して、ページ上の2コンポーネント間で直接通信する場合は、dispatch()->to()
修飾子を使用できます。If you want to use events for communicating directly between two components on the page, you can use the dispatch()->to()
modifier.
以下の例は、CreatePost
コンポーネントがpost-created
イベントをDashboard
コンポーネントへ直接発行し、その特定のイベントをリッスンしている他のコンポーネントをスキップする例です。Below is an example of the CreatePost
component dispatching the post-created
event directly to the Dashboard
component, skipping any other components listening for that specific event:
use Livewire\Component;
class CreatePost extends Component
{
public function save()
{
// ...
$this->dispatch('post-created')->to(Dashboard::class);
}
}
コンポーネントイベントの自身への発行Dispatching a component event to itself
dispatch()->self()
モディファイアを使用すると、イベントをトリガー元のコンポーネントのみが傍受するように制限できます。Using the dispatch()->self()
modifier, you can restrict an event to only being intercepted by the component it was triggered from:
use Livewire\Component;
class CreatePost extends Component
{
public function save()
{
// ...
$this->dispatch('post-created')->self();
}
}
Bladeテンプレートからのイベント発行Dispatching events from Blade templates
$dispatch
JavaScript関数を使用して、Bladeテンプレートから直接イベントを発行できます。これは、ボタンクリックなどのユーザーインタラクションからイベントを発行したい場合に便利です。You can dispatch events directly from your Blade templates using the $dispatch
JavaScript function. This is useful when you want to trigger an event from a user interaction, such as a button click:
<button wire:click="$dispatch('show-post-modal', { id: {{ $post->id }} })">
EditPost
</button>
この例では、ボタンをクリックすると、show-post-modal
イベントが指定したデータとともに発行されます。In this example, when the button is clicked, the show-post-modal
event will be dispatched with the specified data.
別のコンポーネントへ直接イベントを発行したい場合は、$dispatchTo()
JavaScript関数を使用できます。If you want to dispatch an event directly to another component you can use the $dispatchTo()
JavaScript function:
<button wire:click="$dispatchTo('posts', 'show-post-modal', { id: {{ $post->id }} })">
EditPost
</button>
この例では、ボタンをクリックすると、show-post-modal
イベントがPosts
コンポーネントへ直接発行されます。In this example, when the button is clicked, the show-post-modal
event will be dispatched directly to the Posts
component.
発行したイベントのテストTesting dispatched events
コンポーネントが発行したイベントをテストするには、LivewireテストでassertDispatched()
メソッドを使用します。このメソッドは、コンポーネントのライフサイクル中に特定のイベントが発行されたことを確認します。To test events dispatched by your component, use the assertDispatched()
method in your Livewire test. This method checks that a specific event has been dispatched during the component's lifecycle:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Livewire\CreatePost;
use Livewire\Livewire;
class CreatePostTest extends TestCase
{
use RefreshDatabase;
public function test_it_dispatches_post_created_event()
{
Livewire::test(CreatePost::class)
->call('save')
->assertDispatched('post-created');
}
}
この例のテストは、CreatePost
コンポーネントのsave()
メソッドが呼び出されたときに、post-created
イベントが指定されたデータとともに発行されることを保証します。In this example, the test ensures that the post-created
event is dispatched with the specified data when the save()
method is called on the CreatePost
component.
イベントリスナのテストTesting Event Listeners
イベントリスナをテストするには、テスト環境からイベントを発行し、イベントへの応答として期待されるアクションが実行されることを宣言します。To test event listeners, you can dispatch events from the test environment and assert that the expected actions are performed in response to the event:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Livewire\Dashboard;
use Livewire\Livewire;
class DashboardTest extends TestCase
{
use RefreshDatabase;
public function test_it_updates_post_count_when_a_post_is_created()
{
Livewire::test(Dashboard::class)
->assertSee('Posts created: 0')
->dispatch('post-created')
->assertSee('Posts created: 1');
}
}
この例のテストはpost-created
イベントを発行し、Dashboard
コンポーネントがイベントを適切に処理し、更新されたカウントを表示することを確認します。In this example, the test dispatches the post-created
event, then checks that the Dashboard
component properly handles the event and displays the updated count.
Laravel Echoを使用したリアルタイムイベントReal-time events using Laravel Echo
LivewireはLaravel Echoと連携して、WebSocketを使用してWebページにリアルタイム機能を提供します。Livewire pairs nicely with Laravel Echo[https://laravel.com/docs/broadcasting#client-side-installation] to provide real-time functionality on your web-pages using WebSockets.
Warning! Laravel Echoのインストールは必須です: この機能は、Laravel Echoがインストール済みでおり、
window.Echo
オブジェクトがアプリケーションでグローバルに利用可能であることを前提としています。echoのインストールに関する詳細については、Laravel Echoドキュメントを確認してください。[!warning] Installing Laravel Echo is a prerequisite This feature assumes you have installed Laravel Echo and thewindow.Echo
object is globally available in your application. For more information on installing echo, check out the Laravel Echo documentation[https://laravel.com/docs/broadcasting#client-side-installation].
EchoイベントのリッスンListening for Echo events
LaravelアプリケーションにOrderShipped
という名前のイベントがあるとします。Imagine you have an event in your Laravel application named OrderShipped
:
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderShipped implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public Order $order;
public function broadcastOn()
{
return new Channel('orders');
}
}
アプリケーションの別の部分からこのイベントを以下のように発行できます。You might dispatch this event from another part of your application like so:
use App\Events\OrderShipped;
OrderShipped::dispatch();
Laravel Echoのみを使用してJavaScriptでこのイベントをリッスンする場合、次のようになります。If you were to listen for this event in JavaScript using only Laravel Echo, it would look something like this:
Echo.channel('orders')
.listen('OrderShipped', e => {
console.log(e.order)
})
Laravel Echoがインストールおよび構成されていると仮定すると、Livewireコンポーネント内からこのイベントをリッスンできます。Assuming you have Laravel Echo installed and configured, you can listen for this event from inside a Livewire component.
以下は、新しい注文の視覚的な表示をユーザーに示すために、OrderShipped
イベントをリッスンしているOrderTracker
コンポーネントの例です。Below is an example of an OrderTracker
component that is listening for the OrderShipped
event in order to show users a visual indication of a new order:
<?php
namespace App\Livewire;
use Livewire\Attributes\On; // [tl! highlight]
use Livewire\Component;
class OrderTracker extends Component
{
public $showNewOrderNotification = false;
#[On('echo:orders,OrderShipped')]
public function notifyNewOrder()
{
$this->showNewOrderNotification = true;
}
// ...
}
(Order IDなど)変数を含むEchoチャネルがある場合は、#[On]
属性の代わりにgetListeners()
メソッドを介してリスナを定義できます。If you have Echo channels with variables embedded in them (such as an Order ID), you can define listeners via the getListeners()
method instead of the #[On]
attribute:
<?php
namespace App\Livewire;
use Livewire\Attributes\On; // [tl! highlight]
use Livewire\Component;
use App\Models\Order;
class OrderTracker extends Component
{
public Order $order;
public $showOrderShippedNotification = false;
public function getListeners()
{
return [
"echo:orders.{$this->order->id},OrderShipped" => 'notifyShipped',
];
}
public function notifyShipped()
{
$this->showOrderShippedNotification = true;
}
// ...
}
または、必要に応じて、動的なイベント名構文を使用できます。Or, if you prefer, you can use the dynamic event name syntax:
#[On('echo:orders.{order.id},OrderShipped')]
public function notifyNewOrder()
{
$this->showNewOrderNotification = true;
}
イベントペイロードにアクセスする必要がある場合は、渡された$event
パラメータを介してアクセスできます。If you need to access the event payload, you can do so via the passed in $event
parameter:
#[On('echo:orders.{order.id},OrderShipped')]
public function notifyNewOrder($event)
{
$order = Order::find($event['orderId']);
//
}
プライベートチャネルとプレゼンスチャネルPrivate & presence channels
プライベートチャネルとプレゼンスチャネルにブロードキャストされるイベントをリッスンすることもできます。You may also listen to events broadcast to private and presence channels:
認証コールバックを定義していることを確認してください。[!info] Before proceeding, ensure you have defined Authentication Callbacks[https://laravel.com/docs/master/broadcasting#defining-authorization-callbacks] for your broadcast channels.
Info: 続行する前に、ブロードキャストチャネルの
<?php
namespace App\Livewire;
use Livewire\Component;
class OrderTracker extends Component
{
public $showNewOrderNotification = false;
public function getListeners()
{
return [
// Public Channel
"echo:orders,OrderShipped" => 'notifyNewOrder',
// Private Channel
"echo-private:orders,OrderShipped" => 'notifyNewOrder',
// Presence Channel
"echo-presence:orders,OrderShipped" => 'notifyNewOrder',
"echo-presence:orders,here" => 'notifyNewOrder',
"echo-presence:orders,joining" => 'notifyNewOrder',
"echo-presence:orders,leaving" => 'notifyNewOrder',
];
}
public function notifyNewOrder()
{
$this->showNewOrderNotification = true;
}
}