LivewireコンポーネントでのJavaScriptの使用Using JavaScript in Livewire components
LivewireとAlpineは、HTML内で直接動的なコンポーネントを構築するための豊富なユーティリティを提供していますが、HTMLから離れて、コンポーネントのためにプレーンなJavaScriptを実行することが役立つ場合があります。Livewireの@script
と@assets
ディレクティブを使用すると、予測可能で保守しやすい方法でこれを行うことができます。Livewire and Alpine provide plenty of utilities for building dynamic components directly in your HTML, however, there are times when it's helpful to break out of the HTML and execute plain JavaScript for your component. Livewire's @script
and @assets
directive allow you to do this in a predictable, maintainable way.
スクリプトの実行Executing scripts
Livewireコンポーネントで独自のJavaScriptを実行するには、@script
と@endscript
で<script>
要素をラップするだけです。これにより、LivewireはこのJavaScriptの実行を処理するように指示されます。To execute bespoke JavaScript in your Livewire component, simply wrap a <script>
element with @script
and @endscript
. This will tell Livewire to handle the execution of this JavaScript.
@script
内のスクリプトはLivewireによって処理されるため、ページがロードされた後、ただしLivewireコンポーネントがレンダリングされる前の最適なタイミングで実行されます。これは、スクリプトを適切にロードするためにdocument.addEventListener('...')
でラップする必要がなくなったことを意味します。Because scripts inside @script
are handled by Livewire, they are executed at the perfect time after the page has loaded, but before the Livewire component has rendered. This means you no longer need to wrap your scripts in document.addEventListener('...')
to load them properly.
これはまた、遅延ロードまたは条件付きでロードされたLivewireコンポーネントが、ページの初期化後もJavaScriptを実行できることを意味します。This also means that lazily or conditionally loaded Livewire components are still able to execute JavaScript after the page has initialized.
<div>
...
</div>
@script
<script>
// このJavascriptはこのコンポーネントがページにロードされるたびに実行されます...
</script>
@endscript
Livewireコンポーネントで使用されるJavaScriptアクションを登録するようなことができる、より完全な例を次に示します。Here's a more full example where you can do something like register a JavaScript action that is used in your Livewire component.
<div>
<button wire:click="$js.increment">+</button>
</div>
@script
<script>
$js('increment', () => {
console.log('increment')
})
</script>
@endscript
JavaScriptアクションの詳細については、アクションのドキュメントを参照してください。To learn more about JavaScript actions, visit the actions documentation[/docs/actions#javascript-actions].
スクリプトからの$wire
の使用Using $wire
from scripts
JavaScriptに@script
を使用することのもう1つの役立つ機能は、Livewireコンポーネントの$wire
オブジェクトに自動的にアクセスできることです。Another helpful feature of using @script
for your JavaScript is that you automatically have access to your Livewire component's $wire
object.
2秒ごとにコンポーネントをリフレッシュするために単純なsetInterval
を使用する例を次に示します(wire:poll
を使用すると簡単にできますが、ポイントを示す簡単な方法です)。Here's an example of using a simple setInterval
to refresh the component every 2 seconds (You could easily do this with wire:poll
[/docs/wire-poll], but it's a simple way to demonstrate the point):
$wire
の詳細については、$wire
ドキュメントを参照してください。You can learn more about $wire
on the $wire
documentation[#the-wire-object].
@script
<script>
setInterval(() => {
$wire.$refresh()
}, 2000)
</script>
@endscript
一度限りのJavaScript式の評価Evaluating one-off JavaScript expressions
JavaScriptで評価されるメソッド全体を指定するだけでなく、js()
メソッドを使用して、バックエンドでより小さく、個々の式を評価できます。In addition to designating entire methods to be evaluated in JavaScript, you can use the js()
method to evaluate smaller, individual expressions on the backend.
これは通常、サーバ側のアクションが実行された後に、何らかのクライアント側のフォローアップを実行する場合に役立ちます。This is generally useful for performing some kind of client-side follow-up after a server-side action is performed.
たとえば、投稿がデータベースに保存された後、クライアント側のアラートダイアログをトリガーするCreatePost
コンポーネントの例を次に示します。For example, here is an example of a CreatePost
component that triggers a client-side alert dialog after the post is saved to the database:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public $title = '';
public function save()
{
// ...
$this->js("alert('Post saved!')"); // [tl! highlight:6]
}
}
JavaScript式alert('Post saved!')
は、サーバ上のデータベースに投稿が保存された後、クライアントで実行されるようになります。The JavaScript expression alert('Post saved!')
will now be executed on the client after the post has been saved to the database on the server.
式の中で現在のコンポーネントの$wire
オブジェクトにアクセスできます。You can access the current component's $wire
object inside the expression.
アセットのロードLoading assets
@script
ディレクティブは、Livewireコンポーネントがロードされるたびに少しのJavaScriptを実行するのに役立ちますが、コンポーネントと一緒にページ全体にスクリプトおよびスタイルアセットをロードしたい場合があります。The @script
directive is useful for executing a bit of JavaScript every time a Livewire component loads, however, there are times you might want to load entire script and style assets on the page along with the component.
Pikadayと呼ばれる日付ピッカーライブラリをロードし、@script
を使用してコンポーネント内で初期化するために@assets
を使用する例を次に示します。Here is an example of using @assets
to load a date picker library called Pikaday[https://github.com/Pikaday/Pikaday] and initialize it inside your component using @script
:
<div>
<input type="text" data-picker>
</div>
@assets
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js" defer></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
@endassets
@script
<script>
new Pikaday({ field: $wire.$el.querySelector('[data-picker]') });
</script>
@endscript
このコンポーネントがロードされると、Livewireは、@assets
が@script
を評価する前にそのページにロードされていることを確認します。さらに、@script
とは異なり、提供された@assets
が、このコンポーネントのインスタンスがいくつあっても、ページごとに1回だけロードされるようにします。@script
は、ページ上のコンポーネントインスタンスごとに評価されます。When this component loads, Livewire will make sure any @assets
are loaded on that page before evaluating @script
s. In addition, it will ensure the provided @assets
are only loaded once per page no matter how many instances of this component there are, unlike @script
, which will evaluate for every component instance on the page.
グローバルLivewireイベントGlobal Livewire events
Livewireは、外部スクリプトからカスタム拡張ポイントを登録するための2つの役立つブラウザイベントをディスパッチします。Livewire dispatches two helpful browser events for you to register any custom extension points from outside scripts:
<script>
document.addEventListener('livewire:init', () => {
// Livewireがロードされた後、ページで初期化される前に実行されます...
// ページ上で初期化される前に...
})
document.addEventListener('livewire:initialized', () => {
// Livewireがページでの初期化を完了した直後に実行されます...
// ページ上で初期化を完了した直後に...
})
</script>
カスタムディレクティブの登録またはライフサイクルフックを
Info:livewire:init
内で登録すると、Livewireがページでの初期化を開始する前に使用できるようになるため、多くの場合有益です。[!info] It is often beneficial to register any custom directives[#registering-custom-directives] or lifecycle hooks[#javascript-hooks] inside oflivewire:init
so that they are available before Livewire begins initializing on the page.
Livewire
グローバルオブジェクトThe Livewire
global object
Livewireのグローバルオブジェクトは、外部スクリプトからLivewireと対話するための最適な出発点です。Livewire's global object is the best starting point for interacting with Livewire from external scripts.
クライアント側のコード内のどこからでも、window
でグローバルLivewire
JavaScriptオブジェクトにアクセスできます。You can access the global Livewire
JavaScript object on window
from anywhere inside your client-side code.
livewire:init
イベントリスナ内でwindow.Livewire
を使用すると便利なことがよくあります。It is often helpful to use window.Livewire
inside a livewire:init
event listener
コンポーネントへのアクセスAccessing components
次のメソッドを使用して、現在のページにロードされている特定のLivewireコンポーネントにアクセスできます。You can use the following methods to access specific Livewire components loaded on the current page:
// ページ上の最初のコンポーネントの$wireオブジェクトを取得します...
let component = Livewire.first()
// IDで指定されたコンポーネントの`$wire`オブジェクトを取得します...
let component = Livewire.find(id)
// 名前でコンポーネント`$wire`オブジェクトの配列を取得します...
let components = Livewire.getByName(name)
// ページ上のすべてのコンポーネントの`$wire`オブジェクトを取得します...
let components = Livewire.all()
Info: これらの各メソッドは、Livewireのコンポーネントの状態を表す
$wire
オブジェクトを返します。
これらのオブジェクトの詳細については、$wire
ドキュメントを参照してください。[!info] Each of these methods returns a$wire
object representing the component's state in Livewire.
You can learn more about these objects in the$wire
documentation[#the-wire-object].
イベントの操作Interacting with events
PHPの個々のコンポーネントからのイベントのディスパッチとリスニングに加えて、グローバルLivewire
オブジェクトを使用すると、アプリケーションのどこからでもLivewireのイベントシステムを操作できます。In addition to dispatching and listening for events from individual components in PHP, the global Livewire
object allows you to interact with Livewire's event system[/docs/events] from anywhere in your application:
// リスニングしているLivewireコンポーネントにイベントをディスパッチします...
Livewire.dispatch('post-created', { postId: 2 })
// 名前で指定されたLivewireコンポーネントにイベントをディスパッチします...
Livewire.dispatchTo('dashboard', 'post-created', { postId: 2 })
// Livewireコンポーネントからディスパッチされたイベントをリッスンします...
Livewire.on('post-created', ({ postId }) => {
// ...
})
特定のシナリオでは、グローバルなLivewireイベントの登録を解除する必要がある場合があります。たとえば、Alpineコンポーネントとwire:navigate
を使用する場合、ページ間を移動する際にinit
が呼び出されると、複数のリスナが登録される可能性があります。これに対処するには、Alpineによって自動的に呼び出されるdestroy
関数を使用します。この関数内のすべてのリスナをループして登録を解除し、不要な累積を防ぎます。In certain scenarios, you might need to unregister global Livewire events. For instance, when working with Alpine components and wire:navigate
, multiple listeners may be registered as init
is called when navigating between pages. To address this, utilize the destroy
function, automatically invoked by Alpine. Loop through all your listeners within this function to unregister them and prevent any unwanted accumulation.
Alpine.data('MyComponent', () => ({
listeners: [],
init() {
this.listeners.push(
Livewire.on('post-created', (options) => {
// 何かをする...
})
);
},
destroy() {
this.listeners.forEach((listener) => {
listener();
});
}
}));
ライフサイクルフックの使用Using lifecycle hooks
Livewireでは、Livewire.hook()
を使用してグローバルライフサイクルのさまざまな部分にフックできます。Livewire allows you to hook into various parts of its global lifecycle using Livewire.hook()
:
// 指定された内部Livewireフックで実行するコールバックを登録します...
Livewire.hook('component.init', ({ component, cleanup }) => {
// ...
})
LivewireのJavaScriptフックの詳細については、下記を参照してください。More information about Livewire's JavaScript hooks can be found below[#javascript-hooks].
カスタムディレクティブの登録Registering custom directives
Livewireでは、Livewire.directive()
を使用してカスタムディレクティブを登録できます。Livewire allows you to register custom directives using Livewire.directive()
.
以下は、JavaScriptのconfirm()
ダイアログを使用して、アクションがサーバに送信される前に確認またはキャンセルするカスタムwire:confirm
ディレクティブの例です。Below is an example of a custom wire:confirm
directive that uses JavaScript's confirm()
dialog to confirm or cancel an action before it is sent to the server:
<button wire:confirm="Are you sure?" wire:click="delete">Delete post</button>
Livewire.directive()
を使用したwire:confirm
の実装を次に示します。Here is the implementation of wire:confirm
using Livewire.directive()
:
Livewire.directive('confirm', ({ el, directive, component, cleanup }) => {
let content = directive.expression
// 「directive」オブジェクトを使用すると、解析されたディレクティブにアクセスできます。
// たとえば、wire:click.prevent = "deletePost(1)"の値は次のとおりです。
//
// directive.raw = wire:click.prevent
// directive.value = "click"
// directive.modifiers = ['prevent']
// directive.expression = "deletePost(1)"
let onClick = e => {
if (! confirm(content)) {
e.preventDefault()
e.stopImmediatePropagation()
}
}
el.addEventListener('click', onClick, { capture: true })
// ページがアクティブなままである間に、LivewireコンポーネントがDOMから削除された場合に、
// `cleanup()`内にクリーンアップコードを登録します。
// LivewireコンポーネントがDOMから削除された場合に...
cleanup(() => {
el.removeEventListener('click', onClick)
})
})
オブジェクトスキーマObject schemas
LivewireのJavaScriptシステムを拡張する場合は、遭遇する可能性のあるさまざまなオブジェクトを理解することが重要です。When extending Livewire's JavaScript system, it's important to understand the different objects you might encounter.
以下は、Livewireの関連する内部プロパティの網羅的なリファレンスです。Here is an exhaustive reference of each of Livewire's relevant internal properties.
念のため、平均的なLivewireユーザーがこれらと対話することはないかもしれません。これらのオブジェクトのほとんどは、Livewireの内部システムまたは高度なユーザーが利用できます。As a reminder, the average Livewire user may never interact with these. Most of these objects are available for Livewire's internal system or advanced users.
$wire
オブジェクトThe $wire
object
次の一般的なCounter
コンポーネントを考えてみましょう。Given the following generic Counter
component:
<?php
namespace App\Livewire;
use Livewire\Component;
class Counter extends Component
{
public $count = 1;
public function increment()
{
$this->count++;
}
public function render()
{
return view('livewire.counter');
}
}
Livewireは、一般に$wire
と呼ばれるオブジェクトの形式で、サーバ側のコンポーネントのJavaScript表現を公開します。Livewire exposes a JavaScript representation of the server-side component in the form of an object that is commonly referred to as $wire
:
let $wire = {
// すべてのコンポーネントのパブリックプロパティは、$wireで直接アクセスできます...
count: 0,
// すべてのパブリックメソッドは公開され、$wireで呼び出し可能です...
increment() { ... },
// 親コンポーネントが存在する場合、親コンポーネントの`$wire`オブジェクトにアクセスします...
$parent,
// LivewireコンポーネントのルートDOM要素にアクセスします...
$el,
// 現在のLivewireコンポーネントのIDにアクセスします...
$id,
// 名前でプロパティの値を取得します...
// 使用法:$wire.$get('count')
$get(name) { ... },
// 名前でコンポーネントのプロパティを設定します...
// 使用法:$wire.$set('count', 5)
$set(name, value, live = true) { ... },
// ブール値プロパティの値を切り替えます...
$toggle(name, live = true) { ... },
// メソッドを呼び出します...
// 使用法:$wire.$call('increment')
$call(method, ...params) { ... },
// JavaScriptアクションを定義します...
// 使用法:$wire.$js('increment', () => { ... })
$js(name, callback) { ... },
// Livewireプロパティの値を、
// 別の任意Alpineプロパティと絡み合わせます...
// 使用法:<div x-data="{ count: $wire.$entangle('count') }">
$entangle(name, live = false) { ... },
// プロパティの値の変更を監視します...
// 使用法:Alpine.$watch('count', (value, old) => { ... })
$watch(name, callback) { ... },
// サーバにコミットを送信してコンポーネントをリフレッシュします
// HTMLを再レンダリングしてページにスワップします...
$refresh() { ... },
// 上記の`$refresh`と同じです。より技術的な名前です...
$commit() { ... },
// このコンポーネントまたはその子からディスパッチされたイベントをリッスンします...
// 使用法:$wire.$on('post-created', () => { ... })
$on(event, callback) { ... },
// このコンポーネントまたはリクエストからトリガーされたライフサイクルフックをリッスンします...
// 使用法:$wire.$hook('commit', () => { ... })
$hook(name, callback) { ... },
// このコンポーネントからイベントをディスパッチします...
// 使用法:$wire.$dispatch('post-created', { postId: 2 })
$dispatch(event, params = {}) { ... },
// 別のコンポーネントにイベントをディスパッチします...
// 使用法:$wire.$dispatchTo('dashboard', 'post-created', { postId: 2 })
$dispatchTo(otherComponentName, event, params = {}) { ... },
// このコンポーネントのみにイベントをディスパッチします...
$dispatchSelf(event, params = {}) { ... },
// `wire:model`を介さずに、
// ファイルをコンポーネントに直接アップロードするためのJS API...
$upload(
name, // プロパティ名
file, // File JavaScriptオブジェクト
finish = () => { ... }, // アップロードが完了すると実行されます...
error = () => { ... }, // アップロード中にエラーが発生した場合に実行されます...
progress = (event) => { // アップロードの進行状況に合わせて実行されます...
event.detail.progress // 1〜100の整数...
},
) { ... },
// 複数のファイルを同時にアップロードするためのAPI...
$uploadMultiple(name, files, finish, error, progress) { },
// 一時的にアップロードされたが保存されていないアップロードを削除します...
$removeUpload(name, tmpFilename, finish, error) { ... },
// 基になる「コンポーネント」オブジェクトを取得します...
__instance() { ... },
}
$wire
について詳しくは、Livewire のドキュメントにある JavaScript でのプロパティへのアクセスをご覧ください。You can learn more about $wire
in Livewire's documentation on accessing properties in JavaScript[/docs/properties#accessing-properties-from-javascript].
snapshot
オブジェクトThe snapshot
object
ネットワークリクエストごとに、Livewire は PHP コンポーネントを JavaScript で利用できるオブジェクトにシリアライズします。このスナップショットは、コンポーネントを PHP オブジェクトに戻してアンシリアライズするために使用されるため、改ざんを防ぐためのメカニズムが組み込まれています。Between each network request, Livewire serializes the PHP component into an object that can be consumed in JavaScript. This snapshot is used to unserialize the component back into a PHP object and therefore has mechanisms built in to prevent tampering:
let snapshot = {
// コンポーネントのシリアライズされた状態(public プロパティ)...
data: { count: 0 },
// コンポーネントに関する長期的な情報...
memo: {
// コンポーネントの一意の ID...
id: '0qCY3ri9pzSSMIXPGg8F',
// コンポーネントの名前。例:<livewire:[name] />
name: 'counter',
// コンポーネントが最初にロードされた
// Web ページの URI、メソッド、およびロケール。
// これは、元のリクエストから後続のコンポーネント更新リクエスト(コミット)に
// ミドルウェアを再適用するために使用されます...
path: '/',
method: 'GET',
locale: 'en',
// ネストされた「子」コンポーネントのリスト。
// 内部テンプレート ID をキーとし、コンポーネント ID を値とします...
children: [],
// このコンポーネントが「遅延ロード」されたかどうか...
lazyLoaded: false,
// 最後の要求中に発生した
// 検証エラーのリスト...
errors: [],
},
// このスナップショットの安全に暗号化されたハッシュ。
// これにより、悪意のあるユーザーがサーバ上の所有されていないリソースに
// アクセスする目的でスナップショットを改ざんした場合、
// チェックサム検証は失敗し、
// エラーがスローされます...
checksum: '1bc274eea17a434e33d26bcaba4a247a4a7768bd286456a83ea6e9be2d18c1e7',
}
component
オブジェクトThe component
object
ページ上のすべてのコンポーネントには、その状態を追跡し、基盤となる機能を公開する、対応するコンポーネントオブジェクトが舞台裏にあります。これは $wire
よりも 1 つ深いレイヤーです。高度な使用を目的としています。Every component on a page has a corresponding component object behind the scenes keeping track of its state and exposing its underlying functionality. This is one layer deeper than $wire
. It is only meant for advanced usage.
以下は、上記の Counter
コンポーネントの実際のコンポーネントオブジェクトであり、JS コメントに関連するプロパティの説明が記載されています。Here's an actual component object for the above Counter
component with descriptions of relevant properties in JS comments:
let component = {
// コンポーネントのルート HTML 要素...
el: HTMLElement,
// コンポーネントの一意の ID...
id: '0qCY3ri9pzSSMIXPGg8F',
// コンポーネントの「名前」(<livewire:[name] />)...
name: 'counter',
// 最新の「effects」オブジェクト。Effects はサーバラウンドトリップからの「副作用」です。
// これらには、リダイレクト、ファイルダウンロードなどが含まれます...
effects: {},
// コンポーネントの最後に認識されたサーバ側の状態...
canonical: { count: 0 },
// コンポーネントの可変データオブジェクト。
// ライブクライアント側の状態を表します...
ephemeral: { count: 0 },
// `this.ephemeral` のリアクティブバージョン。
// このオブジェクトへの変更は、AlpineJS 式によって取得されます...
reactive: Proxy,
// 通常 Alpine 内で `$wire` として使用される Proxy オブジェクト。
// これは、Livewire コンポーネント用の使いやすい
// JS オブジェクトインターフェイスを提供することを目的としています...
$wire: Proxy,
// ネストされた「子」コンポーネントのリスト。
// 内部テンプレート ID をキーとし、コンポーネント ID を値とします...
children: [],
// このコンポーネントの最後に認識された「snapshot」表現。
// スナップショットはサーバ側のコンポーネントから取得され、
// バックエンドで PHP オブジェクトを再作成するために使用されます...
snapshot: {...},
// 上記のスナップショットの解析されていないバージョン。
// これは、次のラウンドトリップでサーバに送り返すために使用されます。
// JS 解析は PHP エンコーディングを混乱させ、チェックサムの不一致が頻繁に発生するためです。
snapshotEncoded: '{"data":{"count":0},"memo":{"id":"0qCY3ri9pzSSMIXPGg8F","name":"counter","path":"\/","method":"GET","children":[],"lazyLoaded":true,"errors":[],"locale":"en"},"checksum":"1bc274eea17a434e33d26bcaba4a247a4a7768bd286456a83ea6e9be2d18c1e7"}',
}
commit
ペイロードThe commit
payload
ブラウザで Livewire コンポーネントに対してアクションが実行されると、ネットワークリクエストがトリガーされます。そのネットワークリクエストには、1 つまたは複数のコンポーネントと、サーバへのさまざまな指示が含まれています。内部的には、これらのコンポーネントネットワークペイロードは「コミット」と呼ばれます。When an action is performed on a Livewire component in the browser, a network request is triggered. That network request contains one or many components and various instructions for the server. Internally, these component network payloads are called "commits".
「コミット」という用語は、Livewire のフロントエンドとバックエンドの関係について役立つ考え方として選択されました。コンポーネントはフロントエンドでレンダリングおよび操作され、その状態と更新をバックエンドに「コミット」する必要があるアクションが実行されるまで行われます。The term "commit" was chosen as a helpful way to think about Livewire's relationship between frontend and backend. A component is rendered and manipulated on the frontend until an action is performed that requires it to "commit" its state and updates to the backend.
このスキーマは、ブラウザの DevTools のネットワークタブ、または Livewire の JavaScript フック のペイロードで認識できます。You will recognize this schema from the payload in the network tab of your browser's DevTools, or Livewire's JavaScript hooks[#javascript-hooks]:
let commit = {
// Snapshot object...
snapshot: { ... },
// サーバで更新するプロパティの
// キーと値のペアリスト...
updates: {},
// サーバ側で呼び出すメソッド(パラメータ付き)の配列...
calls: [
{ method: 'increment', params: [] },
],
}
JavaScript フックJavaScript hooks
高度なユーザー向けに、Livewire は内部のクライアント側「フック」システムを公開しています。次のフックを使用して、Livewire の機能を拡張したり、Livewire アプリケーションに関する詳細情報を取得したりできます。For advanced users, Livewire exposes its internal client-side "hook" system. You can use the following hooks to extend Livewire's functionality or gain more information about your Livewire application.
コンポーネントの初期化Component initialization
新しいコンポーネントが Livewire によって検出されるたびに(最初のページロード時または後で)、component.init
イベントがトリガーされます。component.init
にフックして、新しいコンポーネントに関連するものをインターセプトまたは初期化できます。Every time a new component is discovered by Livewire — whether on the initial page load or later on — the component.init
event is triggered. You can hook into component.init
to intercept or initialize anything related to the new component:
Livewire.hook('component.init', ({ component, cleanup }) => {
//
})
詳細については、コンポーネントオブジェクトに関するドキュメントを参照してください。For more information, please consult the documentation on the component object[#the-component-object].
DOM 要素の初期化DOM element initialization
新しいコンポーネントが初期化されたときにイベントをトリガーすることに加えて、Livewire は特定の Livewire コンポーネント内の各 DOM 要素に対してイベントをトリガーします。In addition to triggering an event when new components are initialized, Livewire triggers an event for each DOM element within a given Livewire component.
これは、アプリケーション内でカスタム Livewire HTML 属性を提供するために使用できます。This can be used to provide custom Livewire HTML attributes within your application:
Livewire.hook('element.init', ({ component, el }) => {
//
})
DOM Morph フックDOM Morph hooks
DOM モーフィングフェーズ中(Livewire がネットワークラウンドトリップを完了した後)、Livewire は変更されたすべての要素に対して一連のイベントをトリガーします。During the DOM morphing phase—which occurs after Livewire completes a network roundtrip—Livewire triggers a series of events for every element that is mutated.
Livewire.hook('morph.updating', ({ el, component, toEl, skip, childrenOnly }) => {
//
})
Livewire.hook('morph.updated', ({ el, component }) => {
//
})
Livewire.hook('morph.removing', ({ el, component, skip }) => {
//
})
Livewire.hook('morph.removed', ({ el, component }) => {
//
})
Livewire.hook('morph.adding', ({ el, component }) => {
//
})
Livewire.hook('morph.added', ({ el }) => {
//
})
要素ごとに発生するイベントに加えて、Livewire コンポーネントごとに morph
イベントと morphed
イベントが発生します。In addition to the events fired per element, a morph
and morphed
event is fired for each Livewire component:
Livewire.hook('morph', ({ el, component }) => {
// `component` の子要素がモーフィングされる直前に実行されます
})
Livewire.hook('morphed', ({ el, component }) => {
// `component` のすべての子要素がモーフィングされた後に実行されます
})
Commit フックCommit hooks
Livewire リクエストには複数のコンポーネントが含まれているため、request は個々のコンポーネントのリクエストとレスポンスのペイロードを参照するには広すぎる用語です。代わりに、内部的には、Livewire はコンポーネントの更新を commits と呼びます。これは、サーバにコンポーネントの状態を committing することを示しています。Because Livewire requests contain multiple components, request is too broad of a term to refer to an individual component's request and response payload. Instead, internally, Livewire refers to component updates as commits — in reference to committing component state to the server.
これらのフックは commit
オブジェクトを公開します。スキーマの詳細については、commit オブジェクトのドキュメントを参照してください。These hooks expose commit
objects. You can learn more about their schema by reading the commit object documentation[#the-commit-payload].
Commit の準備Preparing commits
commit.prepare
フックは、リクエストがサーバに送信される直前にトリガーされます。これにより、送信リクエストに最後の更新またはアクションを追加する機会が得られます。The commit.prepare
hook will be triggered immediately before a request is sent to the server. This gives you a chance to add any last minute updates or actions to the outgoing request:
Livewire.hook('commit.prepare', ({ component }) => {
// commit ペイロードが収集されてサーバに送信される前に実行されます...
})
Commit のインターセプトIntercepting commits
Livewire コンポーネントがサーバに送信されるたびに、commit が行われます。個々の commit のライフサイクルと内容にフックするために、Livewire は commit
フックを公開しています。Every time a Livewire component is sent to the server, a commit is made. To hook into the lifecycle and contents of an individual commit, Livewire exposes a commit
hook.
このフックは、Livewire commit のリクエストとレスポンスの両方にフックするためのメソッドを提供するため、非常に強力です。This hook is extremely powerful as it provides methods for hooking into both the request and response of a Livewire commit:
Livewire.hook('commit', ({ component, commit, respond, succeed, fail }) => {
// commit のペイロードがサーバに送信される直前に実行されます...
respond(() => {
// レスポンスが受信された後、処理される前に実行されます...
})
succeed(({ snapshot, effects }) => {
// 新しいスナップショットとエフェクトのリストを使用して、
// レスポンスが正常に受信および処理された後に実行されます...
})
fail(() => {
// リクエストの一部が失敗した場合に実行されます...
})
})
Request フックRequest hooks
サーバとの間で送受信される HTTP リクエスト全体にフックする場合は、代わりに request
フックを使用できます。If you would like to instead hook into the entire HTTP request going and returning from the server, you can do so using the request
hook:
Livewire.hook('request', ({ url, options, payload, respond, succeed, fail }) => {
// commit ペイロードがコンパイルされた後、ネットワークリクエストが送信される前に実行されます...
respond(({ status, response }) => {
// レスポンスが受信されたときに実行されます...
// "response" は、await response.text() が実行される前の
// 生の HTTP レスポンスオブジェクトです...
})
succeed(({ status, json }) => {
// レスポンスが受信されたときに実行されます...
// "json" は JSON レスポンスオブジェクトです...
})
fail(({ status, content, preventDefault }) => {
// レスポンスにエラーステータスコードがある場合に実行されます...
// "preventDefault" を使用すると、Livewire の
// デフォルトのエラー処理を無効にできます...
// "content" は生のレスポンスコンテンツです...
})
})
ページ有効期限の動作のカスタマイズCustomizing page expiration behavior
デフォルトのページ有効期限切れダイアログがアプリケーションに適していない場合は、request
フックを使用してカスタムソリューションを実装できます。If the default page expired dialog isn't suitable for your application, you can implement a custom solution using the request
hook:
<script>
document.addEventListener('livewire:init', () => {
Livewire.hook('request', ({ fail }) => {
fail(({ status, preventDefault }) => {
if (status === 419) {
confirm('お客様のカスタムページ有効期限切れの動作...')
preventDefault()
}
})
})
})
</script>
上記のコードをアプリケーションで使用すると、セッションが期限切れになったときにカスタムダイアログが表示されます。With the above code in your application, users will receive a custom dialog when their session has expired.