wire:submit
Livewireでは、wire:submit
ディレクティブを使ってフォームの送信を簡単に処理できます。<form>
要素にwire:submit
を追加すると、Livewireはフォームの送信をインターセプトし、デフォルトのブラウザ処理を防止し、Livewireコンポーネントのメソッドを呼び出します。Livewire makes it easy to handle form submissions via the wire:submit
directive. By adding wire:submit
to a <form>
element, Livewire will intercept the form submission, prevent the default browser handling, and call any Livewire component method.
以下は、wire:submit
を使って「Create Post」フォームの送信を処理する基本的な例です。Here's a basic example of using wire:submit
to handle a "Create Post" form submission:
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
Post::create([
'title' => $this->title,
'content' => $this->content,
]);
$this->redirect('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
<form wire:submit="save"> <!-- [tl! highlight] -->
<input type="text" wire:model="title">
<textarea wire:model="content"></textarea>
<button type="submit">Save</button>
</form>
上記の例では、ユーザーが「Save」をクリックしてフォームを送信すると、wire:submit
がsubmit
イベントをインターセプトし、サーバ上でsave()
アクションを呼び出します。In the above example, when a user submits the form by clicking "Save", wire:submit
intercepts the submit
event and calls the save()
action on the server.
Info: Livewireは自動的に
preventDefault()
を呼び出しますwire:submit
は、他のLivewireイベントハンドラとは異なり、内部的にevent.preventDefault()
を呼び出すため、.prevent
モディファイアは必要ありません。これは、submit
イベントをリッスンしていて、デフォルトのブラウザ処理(エンドポイントへの完全なフォーム送信の実行)を防止したくないインスタンスが非常に少ないためです。[!info] Livewire automatically callspreventDefault()
wire:submit
is different than other Livewire event handlers in that it internally callsevent.preventDefault()
without the need for the.prevent
modifier. This is because there are very few instances you would be listening for thesubmit
event and NOT want to prevent it's default browser handling (performing a full form submission to an endpoint).
Info: Livewireは送信中にフォームを自動的に無効にします デフォルトでは、Livewireがフォーム送信をサーバに送信している間、フォームの送信ボタンを無効にし、すべてのフォーム入力を
readonly
としてマークします。これにより、ユーザーは最初の送信が完了するまで、同じフォームを再度送信できません。[!info] Livewire automatically disables forms while submitting By default, when Livewire is sending a form submission to the server, it will disable form submit buttons and mark all form inputs asreadonly
. This way a user cannot submit the same form again until the initial submission is complete.
Going deeperGoing deeper
wire:submit
は、Livewireが提供する多くのイベントリスナの1つにすぎません。次の2つのページでは、アプリケーションでのwire:submit
の使用に関するより完全なドキュメントを提供しています。wire:submit
is just one of many event listeners that Livewire provides. The following two pages provide much more complete documentation on using wire:submit
in your application:
- Responding to browser events with LivewireResponding to browser events with Livewire[/docs/actions]
- Creating forms in LivewireCreating forms in Livewire[/docs/forms]