Livewire has a lot of actions, which are also called event listeners. For example, we have already used one called wire:submit
to submit a form. Let's see two other actions in this lesson: wire:click
and wire:keydown
.
Usually, wire:click
would be added to a button, and after clicking the button, some method would be called in the Livewire component.
Let's add a button to a post form to validate only the title. First, we need a button in the Blade file with the wire:click
directive.
<form method="POST" wire:submit="save"> <div> <label for="title" class="block font-medium text-sm text-gray-700">Title</label> <input id="title" wire:model="form.title" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm" type="text" /> <button type="button" wire:click="validateTitle" class="block mt-4 px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700"> Validate title </button> @error('form.title') <span class="mt-2 text-sm text-red-600">{{ $message }}</span> @enderror </div> // ...</form>
In the form, we tell that after clicking the button, the validateTitle
methods in the Livewire component need to be called.
And we add the validateTitle
method to the Livewire component.
class CreatePost extends Component{ // ... public function validateTitle(): void { $this->validateOnly('form.title'); } // ...}
After pressing the Validate title
button, we see that only the title is validated.
We can call the same method to validate only the title when the key is pressed. Instead of a button, we need to add wire:keydown
on the input and specify which method to call.
<form method="POST" wire:submit="save"> <div> <label for="title" class="block font-medium text-sm text-gray-700">Title</label> <input id="title" wire:model="form.title" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm" type="text" /> <input id="title" wire:model="form.title" wire:keydown="validateTitle" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm" type="text" /> @error('form.title') <span class="mt-2 text-sm text-red-600">{{ $message }}</span> @enderror </div> // ...</form>
After starting to write the title, the validateTitle
gets called.
Livewire has a lot more of such event listeners. You can check them at the official documentation.