wire:text
wire:text
は、コンポーネントのプロパティまたは式に基づいて、要素のテキストコンテンツを動的に更新するディレクティブです。Bladeの {{ }}
構文を使用するのとは異なり、wire:text
はコンポーネントを再レンダリングするためにネットワークラウンドトリップを必要とせずにコンテンツを更新します。wire:text
is a directive that dynamically updates an element's text content based on a component property or expression. Unlike using Blade's {{ }}
syntax, wire:text
updates the content without requiring a network roundtrip to re-render the component.
Alpineの x-text
ディレクティブに精通している場合、この2つは基本的に同じです。If you are familiar with Alpine's x-text
directive, the two are essentially the same.
基本的な使い方Basic usage
wire:text
を使用して、ネットワークラウンドトリップを待たずに Livewire プロパティの更新を楽観的に表示する例を次に示します。Here's an example of using wire:text
to optimistically show updates to a Livewire property without waiting for a network roundtrip.
use Livewire\Component;
use App\Models\Post;
class ShowPost extends Component
{
public Post $post;
public $likes;
public function mount()
{
$this->likes = $this->post->like_count;
}
public function like()
{
$this->post->like();
$this->likes = $this->post->fresh()->like_count;
}
}
<div>
<button x-on:click="$wire.likes++" wire:click="like">❤️ Like</button>
Likes: <span wire:text="likes"></span>
</div>
ボタンがクリックされると、$wire.likes++
は wire:text
を介して表示されるカウントを即座に更新し、wire:click="like"
はバックグラウンドで変更をデータベースに保持します。When the button is clicked, $wire.likes++
immediately updates the displayed count through wire:text
, while wire:click="like"
persists the change to the database in the background.
このパターンにより、wire:text
は Livewire で楽観的な UI を構築するのに最適です。This pattern makes wire:text
perfect for building optimistic UIs in Livewire.