コンポーネント
コンポーネントは、Livewireアプリケーションの構成要素です。ステートと動作を組み合わせて、フロントエンド用の再利用可能なUIを作成します。ここでは、コンポーネントの作成とレンダリングの基本について説明します。Components are the building blocks of your Livewire application. They combine state and behavior to create reusable pieces of UI for your front end. Here, we'll cover the basics of creating and rendering components.
コンポーネントの作成Creating components
Livewireコンポーネントは、Livewire\Component
を拡張したPHPクラスです。コンポーネントファイルは手動で作成することも、次のArtisanコマンドを使用することもできます。A Livewire component is simply a PHP class that extends Livewire\Component
. You can create component files by hand or use the following Artisan command:
php artisan make:livewire CreatePost
ケバブケースの名前を使用することもできます。If you prefer kebab-cased names, you can use them as well:
php artisan make:livewire create-post
このコマンドを実行すると、Livewireはアプリケーションに2つの新しいファイルを作成します。1つ目はコンポーネントのクラスです:app/Livewire/CreatePost.php
After running this command, Livewire will create two new files in your application. The first will be the component's class: app/Livewire/CreatePost.php
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public function render()
{
return view('livewire.create-post');
}
}
2つ目はコンポーネントのBladeビューです:resources/views/livewire/create-post.blade.php
The second will be the component's Blade view: resources/views/livewire/create-post.blade.php
<div>
{{-- ... --}}
</div>
名前空間構文またはドット表記を使用して、サブディレクトリにコンポーネントを作成できます。たとえば、次のコマンドは、Posts
サブディレクトリにCreatePost
コンポーネントを作成します。You may use namespace syntax or dot-notation to create your components in sub-directories. For example, the following commands will create a CreatePost
component in the Posts
sub-directory:
php artisan make:livewire Posts\\CreatePost
php artisan make:livewire posts.create-post
インラインコンポーネントInline components
コンポーネントが比較的小さい場合は、インラインコンポーネントを作成することもできます。インラインコンポーネントは、ビューテンプレートが別のファイルではなく、render()
メソッドに直接含まれている単一ファイルのLivewireコンポーネントです。If your component is fairly small, you may want to create an inline component. Inline components are single-file Livewire components whose view template is contained directly in the render()
method rather than a separate file:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public function render()
{
return <<<'HTML' // [tl! highlight:4]
<div>
{{-- ここにBladeテンプレートを記述します... --}}
</div>
HTML;
}
}
インラインコンポーネントを作成するには、make:livewire
コマンドに--inline
フラグを追加します。You can create inline components by adding the --inline
flag to the make:livewire
command:
php artisan make:livewire CreatePost --inline
renderメソッドの省略Omitting the render method
コンポーネントのボイラープレートを減らすために、render()
メソッドを完全に省略することができます。Livewireは独自の基盤となるrender()
メソッドを使用し、コンポーネントに対応する慣例的な名前のビューを返します。To reduce boilerplate in your components, you can omit the render()
method entirely and Livewire will use its own underlying render()
method, which returns a view with the conventional name corresponding to your component:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
//
}
上記のコンポーネントがページにレンダリングされる場合、Livewireは自動的にlivewire.create-post
テンプレートを使用してレンダリングされるべきであると判断します。If the component above is rendered on a page, Livewire will automatically determine it should be rendered using the livewire.create-post
template.
コンポーネントのスタブのカスタマイズCustomizing component stubs
次のコマンドを実行して、Livewireが新しいコンポーネントの生成に使用するファイル(またはスタブ)をカスタマイズできます。You can customize the files (or stubs) Livewire uses to generate new components by running the following command:
php artisan livewire:stubs
これにより、アプリケーションに4つの新しいファイルが作成されます。This will create four new files in your application:
stubs/livewire.stub
— 新しいコンポーネントの生成に使用stubs/livewire.stub
— used for generating new componentsstubs/livewire.inline.stub
— インラインコンポーネントの生成に使用stubs/livewire.inline.stub
— used for generating inline componentsstubs/livewire.test.stub
— テストファイルの生成に使用stubs/livewire.test.stub
— used for generating test filesstubs/livewire.view.stub
— コンポーネントビューの生成に使用stubs/livewire.view.stub
— used for generating component views
これらのファイルはアプリケーション内に存在しますが、make:livewire
Artisanコマンドを使用すると、Livewireはファイルの生成時にカスタムスタブを自動的に使用します。Even though these files live in your application, you can still use the make:livewire
Artisan command and Livewire will automatically use your custom stubs when generating files.
プロパティの設定Setting properties
Livewireコンポーネントには、データを格納し、コンポーネントのクラスおよびBladeビュー内で簡単にアクセスできるプロパティがあります。このセクションでは、コンポーネントにプロパティを追加し、アプリケーションで使用するための基本について説明します。Livewire components have properties that store data and can be easily accessed within the component's class and Blade view. This section discusses the basics of adding a property to a component and using it in your application.
Livewireコンポーネントにプロパティを追加するには、コンポーネントクラスでパブリックプロパティを宣言します。たとえば、CreatePost
コンポーネントに$title
プロパティを作成しましょう。To add a property to a Livewire component, declare a public property in your component class. For example, let's create a $title
property in the CreatePost
component:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public $title = 'Post title...';
public function render()
{
return view('livewire.create-post');
}
}
ビューでのプロパティへのアクセスAccessing properties in the view
コンポーネントプロパティは、コンポーネントのBladeビューで自動的に利用可能になります。標準のBlade構文を使用して参照できます。ここでは、$title
プロパティの値を表示します。Component properties are automatically made available to the component's Blade view. You can reference it using standard Blade syntax. Here we'll display the value of the $title
property:
<div>
<h1>Title: "{{ $title }}"</h1>
</div>
このコンポーネントのレンダリングされた出力は次のようになります。The rendered output of this component would be:
<div>
<h1>Title: "Post title..."</h1>
</div>
ビューとの追加データの共有Sharing additional data with the view
ビューからプロパティにアクセスすることに加えて、コントローラから通常行うように、render()
メソッドからビューに明示的にデータを渡すことができます。これは、最初にプロパティとしてデータを保存せずに、追加のデータを渡したい場合に役立ちます。プロパティには特定のパフォーマンスとセキュリティに関する影響があるためです。In addition to accessing properties from the view, you can explicitly pass data to the view from the render()
method, like you might typically do from a controller. This can be useful when you want to pass additional data without first storing it as a property—because properties have specific performance and security implications[/docs/properties#security-concerns].
render()
メソッドでビューにデータを渡すには、ビューインスタンスでwith()
メソッドを使用できます。たとえば、投稿の作成者の名前をビューに渡すとします。この場合、投稿の作成者は現在認証されているユーザーです。To pass data to the view in the render()
method, you can use the with()
method on the view instance. For example, let's say you want to pass the post author's name to the view. In this case, the post's author is the currently authenticated user:
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class CreatePost extends Component
{
public $title;
public function render()
{
return view('livewire.create-post')->with([
'author' => Auth::user()->name,
]);
}
}
これで、コンポーネントのBladeビューから$author
プロパティにアクセスできます。Now you may access the $author
property from the component's Blade view:
<div>
<h1>Title: {{ $title }}</h1>
<span>Author: {{ $author }}</span>
</div>
@foreach
ループへのwire:key
の追加Adding wire:key
to @foreach
loops
@foreach
を使用してLivewireテンプレートでデータをループ処理する場合は、ループによってレンダリングされるルート要素に一意のwire:key
属性を追加する必要があります。When looping through data in a Livewire template using @foreach
, you must add a unique wire:key
attribute to the root element rendered by the loop.
Bladeループ内にwire:key
属性がない場合、Livewireはループが変更されたときに古い要素を新しい位置に適切に一致させることができません。これにより、アプリケーションで診断が難しい多くの問題が発生する可能性があります。Without a wire:key
attribute present within a Blade loop, Livewire won't be able to properly match old elements to their new positions when the loop changes. This can cause many hard to diagnose issues in your application.
たとえば、投稿の配列をループ処理している場合は、wire:key
属性を投稿のIDに設定できます。For example, if you are looping through an array of posts, you may set the wire:key
attribute to the post's ID:
<div>
@foreach ($posts as $post)
<div wire:key="{{ $post->id }}"> <!-- [tl! highlight] -->
<!-- ... -->
</div>
@endforeach
</div>
Livewireコンポーネントをレンダリングしている配列をループ処理している場合は、キーをコンポーネント属性:$key
として設定するか、@livewire
ディレクティブを使用するときに3番目の引数としてキーを渡すことができます。If you are looping through an array that is rendering Livewire components you may set the key as a component attribute :key
or pass the key as a third argument when using the @livewire
directive.
<div>
@foreach ($posts as $post)
<livewire:post-item :$post :key="$post->id">
@livewire(PostItem::class, ['post' => $post], key($post->id))
@endforeach
</div>
プロパティへの入力のバインドBinding inputs to properties
Livewireの最も強力な機能の1つは、「データバインディング」です。これは、ページのフォーム入力とプロパティを自動的に同期させる機能です。One of Livewire's most powerful features is "data binding": the ability to automatically keep properties in-sync with form inputs on the page.
CreatePost
コンポーネントの$title
プロパティを、wire:model
ディレクティブを使用してテキスト入力にバインドしてみましょう。Let's bind the $title
property from the CreatePost
component to a text input using the wire:model
directive:
<form>
<label for="title">Title:</label>
<input type="text" id="title" wire:model="title"> <!-- [tl! highlight] -->
</form>
テキスト入力に加えられた変更はすべて、Livewireコンポーネントの$title
プロパティと自動的に同期されます。Any changes made to the text input will be automatically synchronized with the $title
property in your Livewire component.
Warning! "入力中にコンポーネントがライブ更新されないのはなぜですか?" ブラウザでこれを試して、タイトルが自動的に更新されない理由がわからない場合は、Livewireがコンポーネントを更新するのは、ユーザーがフィールドに入力するときではなく、送信ボタンを押すなどの「アクション」が送信されたときだけであるためです。これにより、ネットワークリクエストが削減され、パフォーマンスが向上します。ユーザーが入力するときに「ライブ」更新を有効にするには、代わりに
wire:model.live
を使用できます。データバインディングの詳細を参照してください。[!warning] "Why isn't my component live updating as I type?" If you tried this in your browser and are confused why the title isn't automatically updating, it's because Livewire only updates a component when an "action" is submitted—like pressing a submit button—not when a user types into a field. This cuts down on network requests and improves performance. To enable "live" updating as a user types, you can usewire:model.live
instead. Learn more about data binding[/docs/properties#data-binding].
Livewireプロパティは非常に強力であり、理解しておくべき重要な概念です。詳細については、Livewireプロパティのドキュメントを確認してください。Livewire properties are extremely powerful and are an important concept to understand. For more information, check out the Livewire properties documentation[/docs/properties].
アクションの呼び出しCalling actions
アクションは、ユーザーの操作を処理したり、特定のタスクを実行したりするLivewireコンポーネント内のメソッドです。ページ上のボタンクリックまたはフォーム送信に応答する場合に役立つことがよくあります。Actions are methods within your Livewire component that handle user interactions or perform specific tasks. They're often useful for responding to button clicks or form submissions on a page.
アクションの詳細については、CreatePost
コンポーネントにsave
アクションを追加しましょう。To learn more about actions, let's add a save
action to the CreatePost
component:
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title;
public function save() // [tl! highlight:8]
{
Post::create([
'title' => $this->title
]);
return redirect()->to('/posts')
->with('status', 'Post created!');
}
public function render()
{
return view('livewire.create-post');
}
}
次に、<form>
要素にwire:submit
ディレクティブを追加して、コンポーネントのBladeビューからsave
アクションを呼び出しましょう。Next, let's call the save
action from the component's Blade view by adding the wire:submit
directive to the <form>
element:
<form wire:submit="save"> <!-- [tl! highlight] -->
<label for="title">Title:</label>
<input type="text" id="title" wire:model="title">
<button type="submit">Save</button>
</form>
「保存」ボタンをクリックすると、Livewireコンポーネントのsave()
メソッドが実行され、コンポーネントが再レンダリングされます。When the "Save" button is clicked, the save()
method in your Livewire component will be executed and your component will re-render.
Livewireアクションの詳細については、アクションのドキュメントを参照してください。To keep learning about Livewire actions, visit the actions documentation[/docs/actions].
コンポーネントのレンダリングRendering components
Livewireコンポーネントをページにレンダリングするには、2つの方法があります。There are two ways to render a Livewire component on a page:
- 既存のBladeビューの中に含める方法Include it within an existing Blade view
- ページ全体のコンポーネントとして、直接ルートへ割り付ける方法Assign it directly to a route as a full-page component
Livewireコンポーネントをレンダリングする最初の方法について説明します。これは2番目の方法よりも簡単です。Let's cover the first way to render your component, as it's simpler than the second.
<livewire:component-name />
構文を使用して、BladeテンプレートにLivewireコンポーネントを含めることができます。You can include a Livewire component in your Blade templates using the <livewire:component-name />
syntax:
<livewire:create-post />
コンポーネントクラスがapp/Livewire/
ディレクトリ内でより深くネストされている場合は、.
文字を使用してディレクトリのネストを示すことができます。たとえば、コンポーネントがapp/Livewire/EditorPosts/CreatePost.php
にあると仮定すると、次のようにレンダリングできます。If the component class is nested deeper within the app/Livewire/
directory, you may use the .
character to indicate directory nesting. For example, if we assume a component is located at app/Livewire/EditorPosts/CreatePost.php
, we may render it like so:
<livewire:editor-posts.create-post />
Warning! kebab-caseを使用する必要があります 上記のスニペットでわかるように、コンポーネント名の_kebab-case_バージョンを使用する必要があります。_StudlyCase_バージョンの名前(
<livewire:CreatePost />
)を使用すると無効になり、Livewireによって認識されません。[!warning] You must use kebab-case As you can see in the snippets above, you must use the kebab-cased version of the component name. Using the StudlyCase version of the name (<livewire:CreatePost />
) is invalid and won't be recognized by Livewire.
コンポーネントへのデータの受け渡しPassing data into components
外部データをLivewireコンポーネントに渡すには、コンポーネントタグの属性を使用できます。これは、特定のデータでコンポーネントを初期化する場合に役立ちます。To pass outside data into a Livewire component, you can use attributes on the component tag. This is useful when you want to initialize a component with specific data.
CreatePost
コンポーネントの$title
プロパティに初期値を渡すには、次の構文を使用できます。To pass an initial value to the $title
property of the CreatePost
component, you can use the following syntax:
<livewire:create-post title="Initial Title" />
動的な値または変数をコンポーネントに渡す必要がある場合は、属性の前にコロンを付けることで、コンポーネント属性にPHP式を記述できます。If you need to pass dynamic values or variables to a component, you can write PHP expressions in component attributes by prefixing the attribute with a colon:
<livewire:create-post :title="$initialTitle" />
コンポーネントに渡されたデータは、mount()
ライフサイクルフックを介してメソッドパラメータとして受信されます。この場合、$title
パラメータをプロパティに割り当てるには、次のようなmount()
メソッドを記述します。Data passed into components is received through the mount()
lifecycle hook as method parameters. In this case, to assign the $title
parameter to a property, you would write a mount()
method like the following:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public $title;
public function mount($title = null)
{
$this->title = $title;
}
// ...
}
この例では、$title
プロパティは「Initial Title」の値で初期化されます。In this example, the $title
property will be initialized with the value "Initial Title".
mount()
メソッドはクラスのコンストラクタと考えることができます。これは、コンポーネントの最初のロード時に実行されますが、ページ内の後続のリクエストでは実行されません。mount()
およびその他の役立つライフサイクルフックの詳細については、ライフサイクルのドキュメントを参照してください。You can think of the mount()
method as a class constructor. It runs on the initial load of the component, but not on subsequent requests within a page. You can learn more about mount()
and other helpful lifecycle hooks within the lifecycle documentation[/docs/lifecycle-hooks].
コンポーネントのボイラープレートコードを削減するために、mount()
メソッドを省略することもできます。Livewireは、渡された値と一致する名前を持つコンポーネントのプロパティを自動的に設定します。To reduce boilerplate code in your components, you can alternatively omit the mount()
method and Livewire will automatically set any properties on your component with names matching the passed in values:
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public $title; // [tl! highlight]
// ...
}
これは、mount()
メソッド内で$title
を割り当てるのと同じです。This is effectively the same as assigning $title
inside a mount()
method.
Warning! これらのプロパティはデフォルトではリアクティブではありません
$title
プロパティは、最初のページロード後に外側の:title="$initialValue"
が変更された場合でも自動的に更新されません。これは、Livewireを使用する際に、特にVueやReactなどのJavaScriptフレームワークを使用し、これらの「パラメータ」がそれらのフレームワークの「リアクティブprops」のように動作すると想定している開発者にとって、よくある混乱のポイントです。ただし、ご心配なく。Livewireでは、propsをリアクティブにすることを選択できます。[!warning] These properties are not reactive by default The$title
property will not update automatically if the outer:title="$initialValue"
changes after the initial page load. This is a common point of confusion when using Livewire, especially for developers who have used JavaScript frameworks like Vue or React and assume these "parameters" behave like "reactive props" in those frameworks. But, don't worry, Livewire allows you to opt-in to making your props reactive[/docs/nesting#reactive-props].
フルページコンポーネントFull-page components
Livewireを使用すると、Laravelアプリケーションのルートにコンポーネントを直接割り当てることができます。これらは「フルページコンポーネント」と呼ばれます。これらを使用して、ロジックとビューを備えたスタンドアロンページを構築し、Livewireコンポーネント内に完全にカプセル化できます。Livewire allows you to assign components directly to a route in your Laravel application. These are called "full-page components". You can use them to build standalone pages with logic and views, fully encapsulated within a Livewire component.
フルページコンポーネントを作成するには、routes/web.php
ファイルでルートを定義し、Route::get()
メソッドを使用してコンポーネントを特定のURLに直接マップします。たとえば、専用ルート/posts/create
でCreatePost
コンポーネントをレンダリングするとします。To create a full-page component, define a route in your routes/web.php
file and use the Route::get()
method to map the component directly to a specific URL. For example, let's imagine you want to render the CreatePost
component at the dedicated route: /posts/create
.
これを行うには、次の行をroutes/web.php
ファイルに追加します。You can accomplish this by adding the following line to your routes/web.php
file:
use App\Livewire\CreatePost;
Route::get('/posts/create', CreatePost::class);
これで、ブラウザで/posts/create
パスにアクセスすると、CreatePost
コンポーネントがフルページコンポーネントとしてレンダリングされます。Now, when you visit the /posts/create
path in your browser, the CreatePost
component will be rendered as a full-page component.
レイアウトファイルLayout files
フルページコンポーネントは、アプリケーションのレイアウト(通常はresources/views/components/layouts/app.blade.php
ファイルで定義されている)を使用することを忘れないでください。Remember that full-page components will use your application's layout, typically defined in the resources/views/components/layouts/app.blade.php
file.
このファイルが存在しない場合は、次のコマンドを実行して作成できます。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
.
この場所にBladeファイルを作成し、{{ $slot }}
プレースホルダーを含めたことを確認してください。Ensure you have created a Blade file at this location and included a {{ $slot }}
placeholder:
<!-- resources/views/components/layouts/app.blade.php -->
<!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>
グローバルレイアウト構成Global layout configuration
すべてのコンポーネントでカスタムレイアウトを使用するには、config/livewire.php
のlayout
キーを、resources/views
に対するカスタムレイアウトのパスに設定します。例:To use a custom layout across all your components, you can set the layout
key in config/livewire.php
to the path of your custom layout, relative to resources/views
. For example:
'layout' => 'layouts.app',
上記の構成では、Livewireはフルページコンポーネントをレイアウトファイルresources/views/layouts/app.blade.php
内でレンダリングします。With the above configuration, Livewire will render full-page components inside the layout file: resources/views/layouts/app.blade.php
.
コンポーネントごとのレイアウト構成Per-component layout configuration
特定のコンポーネントに異なるレイアウトを使用するには、Livewireの#[Layout]
属性をコンポーネントのrender()
メソッドの上に配置し、カスタムレイアウトの相対ビューパスを渡します。To use a different layout for a specific component, you can place Livewire's #[Layout]
attribute above the component's render()
method, passing it the relative view path of your custom layout:
<?php
namespace App\Livewire;
use Livewire\Attributes\Layout;
use Livewire\Component;
class CreatePost extends Component
{
// ...
#[Layout('layouts.app')] // [tl! highlight]
public function render()
{
return view('livewire.create-post');
}
}
または、必要に応じて、この属性をクラス宣言の上に配置できます。Or if you prefer, you can use this attribute above the class declaration:
<?php
namespace App\Livewire;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.app')] // [tl! highlight]
class CreatePost extends Component
{
// ...
}
PHP属性はリテラル値のみをサポートします。動的な値を渡す必要がある場合、またはこの代替構文を希望する場合は、コンポーネントのrender()
メソッドでfluent ->layout()
メソッドを使用できます。PHP attributes only support literal values. If you need to pass a dynamic value, or prefer this alternative syntax, you can use the fluent ->layout()
method in the component's render()
method:
public function render()
{
return view('livewire.create-post')
->layout('layouts.app'); // [tl! highlight]
}
あるいは、Livewireは従来のBladeレイアウトファイルを@extends
で使用することもサポートしています。Alternatively, Livewire supports using traditional Blade layout files with @extends
.
次のレイアウトファイルがあるとします。Given the following layout file:
<body>
@yield('content')
</body>
Livewireが->layout()
の代わりに->extends()
を使用してそれを参照するように構成できます。You can configure Livewire to reference it using ->extends()
instead of ->layout()
:
public function render()
{
return view('livewire.show-posts')
->extends('layouts.app'); // [tl! highlight]
}
コンポーネントが使用する@section
を構成する必要がある場合は、->section()
メソッドを使用してそれも構成できます。If you need to configure the @section
for the component to use, you can configure that as well with the ->section()
method:
public function render()
{
return view('livewire.show-posts')
->extends('layouts.app')
->section('body'); // [tl! highlight]
}
ページタイトルの設定Setting the page title
アプリケーションの各ページに一意のページタイトルを割り当てることは、ユーザーと検索エンジンの両方にとって役立ちます。Assigning unique page titles to each page in your application is helpful for both users and search engines.
フルページコンポーネントのカスタムページタイトルを設定するには、まず、レイアウトファイルに動的なタイトルが含まれていることを確認してください。To set a custom page title for a full-page component, first, make sure your layout file includes a dynamic title:
<head>
<title>{{ $title ?? 'Page Title' }}</title>
</head>
次に、Livewireコンポーネントのrender()
メソッドの上に、#[Title]
属性を追加し、ページタイトルを渡します。Next, above your Livewire component's render()
method, add the #[Title]
attribute and pass it your page title:
<?php
namespace App\Livewire;
use Livewire\Attributes\Title;
use Livewire\Component;
class CreatePost extends Component
{
// ...
#[Title('Create Post')] // [tl! highlight]
public function render()
{
return view('livewire.create-post');
}
}
これにより、CreatePost
Livewireコンポーネントのページタイトルが設定されます。この例では、コンポーネントがレンダーされると、ページタイトルは"Create Post"になります。This will set the page title for the CreatePost
Livewire component. In this example, the page title will be "Create Post" when the component is rendered.
必要に応じて、この属性をクラス宣言の上に配置できます。If you prefer, you can use this attribute above the class declaration:
<?php
namespace App\Livewire;
use Livewire\Attributes\Title;
use Livewire\Component;
#[Title('Create Post')] // [tl! highlight]
class CreatePost extends Component
{
// ...
}
コンポーネントプロパティを使用するタイトルなど、動的なタイトルを渡す必要がある場合は、コンポーネントのrender()
メソッドで、読み書きしやすい->title()
メソッドを使用します。If you need to pass a dynamic title, such as a title that uses a component property, you can use the ->title()
fluent method in the component's render()
method:
public function render()
{
return view('livewire.create-post')
->title('Create Post'); // [tl! highlight]
}
追加のレイアウトファイルスロットの設定Setting additional layout file slots
レイアウトファイルに$slot
に加えて名前付きスロットがある場合は、ルート要素の外側に<x-slot>
を定義して、Bladeビューでそのコンテンツを設定できます。たとえば、各コンポーネントのページ言語を個別に設定できるようにする場合に、レイアウトファイルの開始HTMLタグに動的な$lang
スロットを追加できます。If your layout file[#layout-files] has any named slots in addition to $slot
, you can set their content in your Blade view by defining <x-slot>
s outside your root element. For example, if you want to be able to set the page language for each component individually, you can add a dynamic $lang
slot into the opening HTML tag in your layout file:
<!-- resources/views/components/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', $lang ?? app()->getLocale()) }}"> <!-- [tl! highlight] -->
<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>
コンポーネントのビューで、ルート要素の外側に<x-slot>
要素を定義します。Then, in your component view, define an <x-slot>
element outside the root element:
<x-slot:lang>fr</x-slot> // このコンポーネントはフランス語です <!-- [tl! highlight] -->
<div>
// フランス語のコンテンツがここに入ります...
</div>
ルートパラメータへのアクセスAccessing route parameters
フルページのコンポーネントを使用する際、Livewireコンポーネント内でルートパラメータにアクセスする必要があることも起きるでしょう。When working with full-page components, you may need to access route parameters within your Livewire component.
一例を紹介します。まず、routes/web.php
ファイルへパラメータ付きのルートを定義します。To demonstrate, first, define a route with a parameter in your routes/web.php
file:
use App\Livewire\ShowPost;
Route::get('/posts/{id}', ShowPost::class);
ここでは、投稿のIDを表すid
パラメータを持つルートを定義しました。Here, we've defined a route with an id
parameter which represents a post's ID.
次に、mount()
メソッドでルートパラメータを受け入れるようにLivewireコンポーネントを更新します。Next, update your Livewire component to accept the route parameter in the mount()
method:
<?php
namespace App\Livewire;
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public Post $post;
public function mount($id) // [tl! highlight]
{
$this->post = Post::findOrFail($id);
}
public function render()
{
return view('livewire.show-post');
}
}
この例では、パラメータ名$id
がルートパラメータ{id}
と一致しているため、/posts/1
のURLにアクセスすると、Livewireは"1"の値を$id
として渡します。In this example, because the parameter name $id
matches the route parameter {id}
, if the /posts/1
URL is visited, Livewire will pass the value of "1" as $id
.
ルートモデル結合の使用Using route model binding
Laravelのルートモデル結合を使用すると、ルートパラメータからEloquentモデルを自動的に解決できます。Laravel's route model binding allows you to automatically resolve Eloquent models from route parameters.
routes/web.php
ファイルにモデルパラメータ付きのルートを定義した後:After defining a route with a model parameter in your routes/web.php
file:
use App\Livewire\ShowPost;
Route::get('/posts/{post}', ShowPost::class);
コンポーネントのmount()
メソッドを介して、ルートモデルパラメータを受け取ることができます。You can now accept the route model parameter through the mount()
method of your component:
<?php
namespace App\Livewire;
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public Post $post;
public function mount(Post $post) // [tl! highlight]
{
$this->post = $post;
}
public function render()
{
return view('livewire.show-post');
}
}
mount()
の$post
パラメータにPost
の型ヒントが付いているため、Livewireは「ルートモデル結合」を使用することを知っています。Livewire knows to use "route model binding" because the Post
type-hint is prepended to the $post
parameter in mount()
.
以前と同様に、mount()
メソッドを省略することで定型コードを減らせます。Like before, you can reduce boilerplate by omitting the mount()
method:
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class ShowPost extends Component
{
public Post $post; // [tl! highlight]
public function render()
{
return view('livewire.show-post');
}
}
$post
プロパティは、ルートの{post}
パラメータを介して結びつけたモデルへ自動的に割り当てられます。The $post
property will automatically be assigned to the model bound via the route's {post}
parameter.
レスポンスの変更Modifying the response
シナリオによっては、レスポンスを変更し、カスタムレスポンスヘッダを設定したい場合があるでしょう。ビューのresponse()
メソッドを呼び出し、クロージャを使用してレスポンスオブジェクトを変更することで、レスポンスオブジェクトにフックできます。In some scenarios, you might want to modify the response and set a custom response header. You can hook into the response object by calling the response()
method on the view and use a closure to modify the response object:
<?php
namespace App\Livewire;
use Livewire\Component;
use Illuminate\Http\Response;
class ShowPost extends Component
{
public function render()
{
return view('livewire.show-post')
->response(function(Response $response) {
$response->header('X-Custom-Header', true);
});
}
}
JavaScriptの使用Using JavaScript
LivewireおよびAlpineの組み込みユーティリティだけでは、Livewireコンポーネント内で目標を達成するのに十分ではないインスタンスは数多く存在します。There are many instances where the built-in Livewire and Alpine utilities aren't enough to accomplish your goals inside your Livewire components.
幸いなことに、Livewireは、カスタムJavaScriptを操作するため、多くの便利な拡張ポイントとユーティリティを提供しています。JavaScriptのドキュメントページのリファレンスで詳細を学べます。しかし、ここでは、Livewireコンポーネント内で独自のJavaScriptを使用するために役立つ方法をいくつか紹介します。Fortunately, Livewire provides many useful extension points and utilities to interact with bespoke JavaScript. You can learn from the exhaustive reference on the JavaScript documentation page[/docs/javascript]. But for now, here are a few useful ways to use your own JavaScript inside your Livewire components.
スクリプトの実行Executing scripts
Livewireは<script>
要素をラップし、コンポーネントをページ上で初期化するときに、指定JavaScriptを実行するのに役立つ@script
ディレクティブを提供しています。Livewire provides a helpful @script
directive that, when wrapping a <script>
element, will execute the given JavaScript when your component is initialized on the page.
JavaScriptのsetInterval()
を使用して、コンポーネントを2秒ごとにリフレッシュする簡単な@script
の例を次に示します。Here is an example of a simple @script
that uses JavaScript's setInterval()
to refresh your component every two seconds:
@script
<script>
setInterval(() => {
$wire.$refresh()
}, 2000)
</script>
@endscript
コンポーネントを制御するために、<script>
内で$wire
というオブジェクトを使用していることに気付くでしょう。Livewireは@script
内で、このオブジェクトを自動的に利用できるようにしています。$wire
に慣れていない場合、以下のドキュメントで$wire
について詳しく学んでください。You'll notice we are using an object called $wire
inside the <script>
to control the component. Livewire automatically makes this object available inside any @script
s. If you're unfamiliar with $wire
, you can learn more about $wire
in the following documentation:
- JavaScriptからプロパティへのアクセスAccessing properties from JavaScript[/docs/properties#accessing-properties-from-javascript]
- JS/AlpineからのLivewireアクションの呼び出しCalling Livewire actions from JS/Alpine[/docs/actions#calling-actions-from-alpine]
$wire
オブジェクトリファレンスThe$wire
object reference[/docs/javascript#the-wire-object]
アセットのロードLoading assets
1回限りの@script
に加えて、Livewireは、ページにスクリプト/スタイルの依存関係を簡単にロードするのに便利な、@assets
ユーティリティを提供しています。In addition to one-off @script
s, Livewire provides a helpful @assets
utility to easily load any script/style dependencies on the page.
また、Livewireコンポーネントの新しいインスタンスを初期化するたび実行する@script
とは異なり、指定したアセットがブラウザページで一度だけロードするようにします。It also ensures that the provided assets are loaded only once per browser page, unlike @script
, which executes every time a new instance of that Livewire component is initialized.
@assets
を使用してPikadayと名前の日付ピッカーライブラリをロードし、@script
を使用してコンポーネント内で初期化する例を次に示します。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
Info: Bladeコンポーネント内での
@verbatim@script@endverbatim
と@verbatim@assets@endverbatim
の使用: Bladeコンポーネントを使用してマークアップの一部を抽出している場合は、同じLivewireコンポーネント内に複数のBladeコンポーネントがある場合でも、その中で@verbatim@script@endverbatim
と@verbatim@assets@endverbatim
を使用できます。ただし、@verbatim@script@endverbatim
と@verbatim@assets@endverbatim
は現在、Livewireコンポーネントのコンテキストでのみサポートしています。つまり、Livewireの外部で指定されたBladeコンポーネントを使用する場合、こうしたスクリプトとアセットをページにロードしません。[!info] Using@verbatim@script@endverbatim
and@verbatim@assets@endverbatim
inside Blade components If you are using Blade components[https://laravel.com/docs/blade#components] to extract parts of your markup, you can use@verbatim@script@endverbatim
and@verbatim@assets@endverbatim
inside them as well; even if there are multiple Blade components inside the same Livewire component. However,@verbatim@script@endverbatim
and@verbatim@assets@endverbatim
are currently only supported in the context of a Livewire component, meaning if you use the given Blade component outside of Livewire entirely, those scripts and assets won't be loaded on the page.