Readouble

Livewire v3 クイックスタート

クイックスタート

Livewireの旅を始めるにあたり、シンプルな「カウンター」コンポーネントを作成し、ブラウザへレンダーしましょう。この例は、Livewireの活力を最も簡単に体験できるため、初めてLivewireを体験するには最適です。To begin your Livewire journey, we will create a simple "counter" component and render it in the browser. This example is a great way to experience Livewire for the first time as it demonstrates Livewire's liveness in the simplest way possible.

前提条件Prerequisites

始める前に、以下がインストール済みであることを確認してください。Before we start, make sure you have the following installed:

  • Laravel version10以降Laravel version 10 or later
  • PHP version8.1以降PHP version 8.1 or later

LivewireのインストールInstall Livewire

Laravelアプリのルートディレクトリから、次の Composerコマンドを実行します。From the root directory of your Laravel app, run the following Composer[https://getcomposer.org/] command:

composer require livewire/livewire

warning Warning! Alpineがまだインストールされていないことを確認してください。 使用しているアプリケーションでAlpineJSをすでにインストールしている場合は、Livewireを正常に動作させるために削除する必要があります。そうしないと、Alpineが2回ロードされ、Livewireが機能しません。たとえば、Laravel Breezeの「Alpineを使用するBlade」スターターキットをインストールした場合、resources/js/app.jsからAlpineを削除する必要があります。[!warning] Make sure Alpine isn't already installed If the application you are using already has AlpineJS installed, you will need to remove it for Livewire to work properly; otherwise, Alpine will be loaded twice and Livewire won't function. For example, if you installed the Laravel Breeze "Blade with Alpine" starter kit, you will need to remove Alpine from resources/js/app.js.

Livewireコンポーネントの作成Create a Livewire component

Livewireには、新しいコンポーネントをすばやく生成するために、便利なArtisanコマンドを用意しています。次のコマンドを実行して、新しいCounterコンポーネントを作成してください。Livewire provides a convenient Artisan command to generate new components quickly. Run the following command to make a new Counter component:

php artisan make:livewire counter

このコマンドにより、プロジェクトに以下の新しい2ファイルが生成されます。This command will generate two new files in your project:

  • app/Livewire/Counter.phpapp/Livewire/Counter.php
  • resources/views/livewire/counter.blade.phpresources/views/livewire/counter.blade.php

クラスの記述Writing the class

app/Livewire/Counter.phpを開き、その内容を以下に置き換えます。Open app/Livewire/Counter.php and replace its contents with the following:

<?php

namespace App\Livewire;

use Livewire\Component;

class Counter extends Component
{
    public $count = 1;

    public function increment()
    {
        $this->count++;
    }

    public function decrement()
    {
        $this->count--;
    }

    public function render()
    {
        return view('livewire.counter');
    }
}

上記のコードの簡単な説明を以下に示します。Here's a brief explanation of the code above:

  • public $count = 1;$countという名前のpublicプロパティを初期値1で宣言します。public $count = 1; — Declares a public property named $count with an initial value of 1.
  • public function increment()increment() という名前のpublicメソッドを宣言します。このメソッドは、呼び出されるたびに$countプロパティをインクリメントします。このようなpublicメソッドは、ユーザーがボタンをクリックするなど、さまざまな方法でブラウザから起動できます。public function increment() — Declares a public method named increment() that increments the $count property each time it's called. Public methods like this can be triggered from the browser in a variety of ways, including when a user clicks a button.
  • public function render() ⇐ Bladeビューを返すrender()メソッドを宣言します。このBladeビューは、コンポーネントのHTMLテンプレートを含みます。public function render() — Declares a render() method that returns a Blade view. This Blade view will contain the HTML template for our component.

ビューの記述Writing the view

resources/views/livewire/counter.blade.phpファイルを開き、その内容を以下に置き換えます。Open the resources/views/livewire/counter.blade.php file and replace its content with the following:

<div>
    <h1>{{ $count }}</h1>

    <button wire:click="increment">+</button>

    <button wire:click="decrement">-</button>
</div>

このコードは、$countプロパティの値を表示し、加えて$countプロパティをそれぞれ増分および減分する2つのボタンを表示します。This code will display the value of the $count property and two buttons that increment and decrement the $count property, respectively.

warning Warning! Livewireコンポーネントには、単一のルート要素が必須です。 Livewireが動作するためには、コンポーネントはルートとして1つの単一要素を持つ必要があります。複数のルート要素を検出すると、例外を投げます。例のように、<div>要素を使用することをお勧めします。HTMLコメントは個別の要素としてカウントされ、ルート要素の内側に配置する必要があります。 フルページコンポーネントをレンダーする場合、レイアウトファイルの名前付きスロットは、ルート要素の外側に配置できます。これらは、コンポーネントをレンダーする前に削除します。[!warning] Livewire components MUST have a single root element In order for Livewire to work, components must have just one single element as its root. If multiple root elements are detected, an exception is thrown. It is recommended to use a <div> element as in the example. HTML comments count as separate elements and should be put inside the root element. When rendering full-page components[/docs/components#full-page-components], named slots for the layout file may be put outside the root element. These are removed before the component is rendered.

コンポーネントのルート登録Register a route for the component

Laravelアプリケーションのroutes/web.phpファイルを開き、次のコードを追加します。Open the routes/web.php file in your Laravel application and add the following code:

use App\Livewire\Counter;

Route::get('/counter', Counter::class);

これにより、カウンターコンポーネントを/counterルートへ割り当てます。ユーザーがアプリケーションの/counterエンドポイントへアクセスすると、このコンポーネントがブラウザでレンダーされます。Now, our counter component is assigned to the /counter route, so that when a user visits the /counter endpoint in your application, this component will be rendered by the browser.

テンプレートレイアウトの作成Create a template layout

ブラウザで/counterへアクセスする前に、コンポーネントをレンダーするためのHTMLレイアウトが必要です。デフォルトでは、Livewireは以下の名前のレイアウトファイルを自動的に検索します。resources/views/components/layouts/app.blade.phpBefore you can visit /counter in the browser, we need an HTML layout for our component to render inside. By default, Livewire will automatically look for a layout file named: resources/views/components/layouts/app.blade.php

このファイルが存在しない場合は、次のコマンドを実行して作成してください。You may create this file if it doesn't already exist by running the following command:

php artisan livewire:layout

このコマンドにより、以下の内容を含むresources/views/components/layouts/app.blade.phpファイルが生成されます。This command will generate a file called resources/views/components/layouts/app.blade.php with the following contents:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>{{ $title ?? 'Page Title' }}</title>
    </head>
    <body>
        {{ $slot }}
    </body>
</html>

カウンターコンポーネントは、上記のテンプレートの$slot変数の場所にレンダーされます。The counter component will be rendered in place of the $slot variable in the template above.

Livewireが提供するJavaScriptやCSSアセットがないことに気付いたかもしれません。これは、Livewire3以降では、必要なフロントエンドアセットを自動的に挿入するからです。You may have noticed there is no JavaScript or CSS assets provided by Livewire. That is because Livewire 3 and above automatically injects any frontend assets it needs.

試してみるTest it out

コンポーネントクラスとテンプレートが完成したので、コンポーネントをテストする準備ができました。With our component class and templates in place, our component is ready to test!

ブラウザで/counterへアクセスすると、画面に数字が表示され、その数字を増分および減分するために2ボタンが表示されます。Visit /counter in your browser, and you should see a number displayed on the screen with two buttons to increment and decrement the number.

ボタンのどちらかをクリックすると、ページをリロードせずに、カウントがリアルタイムで更新されることがわかります。これがLivewireの魔法です。完全にPHPで記述された動的なフロントエンドアプリケーションです。After clicking one of the buttons, you will notice that the count updates in real time, without the page reloading. This is the magic of Livewire: dynamic frontend applications written entirely in PHP.

ここまで、Livewireの機能の表面をなぞったにすぎません。ドキュメントを読み続けて、Livewireが提供するすべての機能を確認してください。We've barely scratched the surface of what Livewire is capable of. Keep reading the documentation to see everything Livewire has to offer.

章選択

パッケージ

設定

バージョン変更
linkv3 linkv2
明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作