[!warning] Get comfortable with Livewire first Before using Volt, we recommend getting familiar with standard, class-based Livewire usage. This will allow you to quickly transfer your knowledge of Livewire into writing components using Volt's functional API.
Warning! まずはLivewireに慣れてください Voltを使用する前に、標準的なクラスベースのLivewireの使い方に慣れることをお勧めします。そうすることで、Livewireの知識をVoltの関数型APIを使用したコンポーネントの記述に素早く移行できます。
Voltは、Livewireのためにエレガントに作成された関数型APIで、単一ファイルコンポーネントをサポートしており、コンポーネントのPHPロジックとBladeテンプレートを同じファイル内に共存させることができます。内部的には、この関数型APIはLivewireのクラスコンポーネントにコンパイルされ、同じファイルにあるテンプレートとリンクされます。Volt is an elegantly crafted functional API for Livewire that supports single-file components, allowing a component's PHP logic and Blade templates to coexist in the same file. Behind the scenes, the functional API is compiled to Livewire class components and linked with the template present in the same file.
シンプルなVoltコンポーネントは次のようになります。A simple Volt component looks like the following:
<?php
use function Livewire\Volt\{state};
state(['count' => 0]);
$increment = fn () => $this->count++;
?>
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
インストールInstallation
開始するには、Composerパッケージマネージャーを使用してVoltをプロジェクトにインストールします。To get started, install Volt into your project using the Composer package manager:
composer require livewire/volt
Voltをインストールしたら、volt:install
Artisanコマンドを実行して、Voltのサービスプロバイダーファイルをアプリケーションにインストールできます。このサービスプロバイダーは、Voltが単一ファイルコンポーネントを検索するマウントされたディレクトリを指定します。After installing Volt, you may execute the volt:install
Artisan command, which will install Volt's service provider file into your application. This service provider specifies the mounted directories in which Volt will search for single file components:
php artisan volt:install
コンポーネントの作成Creating components
Voltコンポーネントを作成するには、.blade.php
拡張子を持つファイルを、Voltがマウントされている任意のディレクトリに配置します。デフォルトでは、VoltServiceProvider
はresources/views/livewire
とresources/views/pages
ディレクトリをマウントしますが、これらのディレクトリはVoltのサービスプロバイダーのboot
メソッドでカスタマイズできます。You may create a Volt component by placing a file with the .blade.php
extension in any of your Volt mounted directories. By default, the VoltServiceProvider
mounts the resources/views/livewire
and resources/views/pages
directories, but you may customize these directories in your Volt service provider's boot
method.
便宜上、make:volt
Artisanコマンドを使用して、新しいVoltコンポーネントを作成できます。For convenience, you may use the make:volt
Artisan command to create a new Volt component:
php artisan make:volt counter
コンポーネントの生成時に--test
ディレクティブを追加すると、対応するテストファイルも生成されます。関連するテストでPestを使用する場合は、--pest
フラグを使用する必要があります。By adding the --test
directive when generating a component, a corresponding test file will also be generated. If you want the associated test to use Pest[https://pestphp.com/], you should use the --pest
flag:
php artisan make:volt counter --test --pest
--class
ディレクティブを追加すると、クラスベースのvoltコンポーネントが生成されます。By adding the --class
directive it will generate a class-based volt component.
php artisan make:volt counter --class
APIスタイルAPI style
Voltの関数型APIを利用することで、インポートされたLivewire\Volt
関数を通じてLivewireコンポーネントのロジックを定義できます。Voltは、関数型コードを従来のLivewireクラスに変換およびコンパイルし、ボイラープレートを削減してLivewireの広範な機能を活用できるようにします。By utilizing Volt's functional API, we can define a Livewire component's logic through imported Livewire\Volt
functions. Volt then transforms and compiles the functional code into a conventional Livewire class, enabling us to leverage the extensive capabilities of Livewire with reduced boilerplate.
VoltのAPIは、それが使用するすべてのクロージャを基になるコンポーネントに自動的にバインドします。そのため、アクション、算出プロパティ、またはリスナは、いつでも$this
変数を使用してコンポーネントを参照できます。Volt's API automatically binds any closure it uses to the underlying component. So, at any time, actions, computed properties, or listeners can refer to the component using the $this
variable:
use function Livewire\Volt\{state};
state(['count' => 0]);
$increment = fn () => $this->count++;
// ...
クラスベースのVoltコンポーネントClass-based Volt components
クラスベースのコンポーネントを記述しながら、Voltの単一ファイルコンポーネントの機能を利用したい場合は、それも可能です。開始するには、Livewire\Volt\Component
を拡張する匿名クラスを定義します。クラス内では、従来のLivewire構文を使用してLivewireのすべての機能を利用できます。If you would like to enjoy the single-file component capabilities of Volt while still writing class-based components, we've got you covered. To get started, define an anonymous class that extends Livewire\Volt\Component
. Within the class, you may utilize all of the features of Livewire using traditional Livewire syntax:
<?php
use Livewire\Volt\Component;
new class extends Component {
public $count = 0;
public function increment()
{
$this->count++;
}
} ?>
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
クラス属性Class attributes
通常のLivewireコンポーネントと同様に、Voltコンポーネントはクラス属性をサポートします。匿名PHPクラスを使用する場合、クラス属性はnew
キーワードの後に定義する必要があります。Just like typical Livewire components, Volt components support class attributes. When utilizing anonymous PHP classes, class attributes should be defined after the new
keyword:
<?php
use Livewire\Attributes\{Layout, Title};
use Livewire\Volt\Component;
new
#[Layout('layouts.guest')]
#[Title('Login')]
class extends Component
{
public string $name = '';
// ...
追加のビューデータの提供Providing additional view data
クラスベースのVoltコンポーネントを使用する場合、レンダリングされるビューは同じファイルにあるテンプレートです。ビューがレンダリングされるたびに追加のデータをビューに渡す必要がある場合は、with
メソッドを使用できます。このデータは、コンポーネントのpublicプロパティに加えてビューに渡されます。When using class-based Volt components, the rendered view is the template present in the same file. If you need to pass additional data to the view each time it is rendered, you may use the with
method. This data will be passed to the view in addition to the component's public properties:
<?php
use Livewire\WithPagination;
use Livewire\Volt\Component;
use App\Models\Post;
new class extends Component {
use WithPagination;
public function with(): array
{
return [
'posts' => Post::paginate(10),
];
}
} ?>
<div>
<!-- ... -->
</div>
ビューインスタンスの変更Modifying the view instance
場合によっては、ビューインスタンスを直接操作したい場合があります。たとえば、翻訳された文字列を使用してビューのタイトルを設定するなどです。これを実現するには、コンポーネントにrendering
メソッドを定義します。Sometimes, you may wish to interact with the view instance directly, for example, to set the view's title using a translated string. To achieve this, you may define a rendering
method on your component:
<?php
use Illuminate\View\View;
use Livewire\Volt\Component;
new class extends Component {
public function rendering(View $view): void
{
$view->title('Create Post');
// ...
}
// ...
コンポーネントのレンダリングとマウントRendering and mounting components
通常のLivewireコンポーネントと同様に、VoltコンポーネントはLivewireのタグ構文または@livewire
Bladeディレクティブを使用してレンダリングできます。Just like a typical Livewire component, Volt components may be rendered using Livewire's tag syntax or the @livewire
Blade directive:
<livewire:user-index :users="$users" />
コンポーネントが受け入れるプロパティを宣言するには、state
関数を使用できます。To declare the component's accepted properties, you may use the state
function:
use function Livewire\Volt\{state};
state('users');
// ...
必要に応じて、コンポーネントに渡されるプロパティをインターセプトするために、state
関数にクロージャを指定することで、指定された値と対話し変更できます。If necessary, you can intercept the properties passed to the component by providing a closure to the state
function, allowing you to interact with and modify the given value:
use function Livewire\Volt\{state};
state(['count' => fn ($users) => count($users)]);
mount
関数は、Livewireコンポーネントの「マウント」ライフサイクル フックを定義するために使用できます。コンポーネントに指定されたパラメータは、このメソッドに注入されます。マウントフックに必要なその他のパラメータは、Laravelのサービスコンテナによって解決されます。The mount
function may be used to define the "mount" lifecycle hook[/docs/lifecycle-hooks] of the Livewire component. The parameters provided to the component will be injected into this method. Any other parameters required by the mount hook will be resolved by Laravel's service container:
use App\Services\UserCounter;
use function Livewire\Volt\{mount};
mount(function (UserCounter $counter, $users) {
$counter->store('userCount', count($users));
// ...
});
フルページコンポーネントFull-page components
オプションで、アプリケーションのroutes/web.php
ファイルにVoltルートを定義することで、Voltコンポーネントをフルページコンポーネントとしてレンダリングできます。Optionally, you may render a Volt component as a full page component by defining a Volt route in your application's routes/web.php
file:
use Livewire\Volt\Volt;
Volt::route('/users', 'user-index');
デフォルトでは、コンポーネントはcomponents.layouts.app
レイアウトを使用してレンダリングされます。layout
関数を使用して、このレイアウトファイルをカスタマイズできます。By default, the component will be rendered using the components.layouts.app
layout. You may customize this layout file using the layout
function:
use function Livewire\Volt\{layout, state};
state('users');
layout('components.layouts.admin');
// ...
title
関数を使用して、ページのタイトルをカスタマイズすることもできます。You may also customize the title of the page using the title
function:
use function Livewire\Volt\{layout, state, title};
state('users');
layout('components.layouts.admin');
title('Users');
// ...
タイトルがコンポーネントの状態または外部依存関係に依存する場合は、代わりにtitle
関数にクロージャを渡すことができます。If the title relies on component state or an external dependency, you may pass a closure to the title
function instead:
use function Livewire\Volt\{layout, state, title};
state('users');
layout('components.layouts.admin');
title(fn () => 'Users: ' . $this->users->count());
プロパティProperties
Voltプロパティは、Livewireプロパティと同様に、ビューで簡単にアクセスでき、Livewireの更新間で保持されます。state
関数を使用してプロパティを定義できます。Volt properties, like Livewire properties, are conveniently accessible in the view and persist between Livewire updates. You can define a property using the state
function:
<?php
use function Livewire\Volt\{state};
state(['count' => 0]);
?>
<div>
{{ $count }}
</div>
状態プロパティの初期値が、データベースクエリ、モデル、またはコンテナサービスなどの外部依存関係に依存している場合は、その解決をクロージャ内にカプセル化する必要があります。これにより、値が絶対に必要になるまで解決されるのを防ぎます。If the initial value of a state property relies on outside dependencies, such as database queries, models, or container services, its resolution should be encapsulated within a closure. This prevents the value from being resolved until it is absolutely necessary:
use App\Models\User;
use function Livewire\Volt\{state};
state(['count' => fn () => User::count()]);
状態プロパティの初期値がLaravel Folioのルートモデルバインディングを介して注入されている場合も、クロージャ内にカプセル化する必要があります。If the initial value of a state property is being injected via Laravel Folio's[https://github.com/laravel/folio] route model binding, it should also be encapsulated within a closure:
use App\Models\User;
use function Livewire\Volt\{state};
state(['user' => fn () => $user]);
もちろん、プロパティは初期値を明示的に指定せずに宣言することもできます。このような場合、初期値はnull
になるか、レンダリング時にコンポーネントに渡されるプロパティに基づいて設定されます。Of course, properties may also be declared without explicitly specifying their initial value. In such cases, their initial value will be null
or will be set based on the properties passed into the component when it is rendered:
use function Livewire\Volt\{mount, state};
state(['count']);
mount(function ($users) {
$this->count = count($users);
//
});
ロックされたプロパティLocked properties
Livewireは、プロパティを「ロック」することで保護し、クライアント側で変更が発生しないようにする機能を提供します。Voltを使用してこれを実現するには、保護したいstateに対してlocked
メソッドをチェーンするだけです。Livewire offers the ability to safeguard properties by enabling you to "lock" them, thereby preventing any modifications from occurring on the client-side. To achieve this using Volt, simply chain the locked
method on the state you wish to protect:
state(['id'])->locked();
リアクティブなプロパティReactive properties
ネストされたコンポーネントを扱う場合、親コンポーネントから子コンポーネントにプロパティを渡し、親コンポーネントがプロパティを更新したときに子コンポーネントが自動的に更新される必要がある状況に遭遇することがあります。When working with nested components, you may find yourself in a situation where you need to pass a property from a parent component to a child component, and have the child component automatically update[/docs/nesting#reactive-props] when the parent component updates the property.
Voltを使用してこれを実現するには、リアクティブにしたいstateに対してreactive
メソッドをチェーンします。To achieve this using Volt, you may chain the reactive
method on the state you wish to be reactive:
state(['todos'])->reactive();
ModelableなプロパティModelable properties
リアクティブなプロパティを使用しない場合、Livewireは、wire:model
を使用して親コンポーネントと子コンポーネント間で直接stateを共有できるmodelableな機能を提供します。In cases where you don't want to make use of reactive properties, Livewire provides a modelable feature[/docs/nesting#binding-to-child-data-using-wiremodel] where you may share state between parent component and child component using wire:model
directly on a child component.
Voltを使用してこれを実現するには、modelableにしたいstateに対してmodelable
メソッドをチェーンするだけです。To achieve this using Volt, simply chain the modelable
method on the state you wish to be modelable:
state(['form'])->modelable();
算出プロパティComputed properties
Livewireでは、算出プロパティを定義することもできます。これは、コンポーネントに必要な情報を遅延ロードするのに役立ちます。算出プロパティの結果は、個々のLivewireリクエストライフサイクルにおいて「メモ化」またはメモリにキャッシュされます。Livewire also allows you to define computed properties[/docs/computed-properties], which can be useful for lazily fetching information needed by your component. Computed property results are "memoized", or cached in memory, for an individual Livewire request lifecycle.
算出プロパティを定義するには、computed
関数を使用します。変数の名前が算出プロパティの名前を決定します。To define a computed property, you may use the computed
function. The name of the variable will determine the name of the computed property:
<?php
use App\Models\User;
use function Livewire\Volt\{computed};
$count = computed(function () {
return User::count();
});
?>
<div>
{{ $this->count }}
</div>
算出プロパティの値をアプリケーションのキャッシュに永続化するには、算出プロパティの定義にpersist
メソッドをチェーンします。You may persist the computed property's value in your application's cache by chaining the persist
method onto the computed property definition:
$count = computed(function () {
return User::count();
})->persist();
デフォルトでは、Livewireは算出プロパティの値を3600秒間キャッシュします。persist
メソッドに必要な秒数を指定することで、この値をカスタマイズできます。By default, Livewire caches the computed property's value for 3600 seconds. You may customize this value by providing the desired number of seconds to the persist
method:
$count = computed(function () {
return User::count();
})->persist(seconds: 10);
アクションActions
Livewire アクションは、ページインタラクションをリッスンし、コンポーネントに対応するメソッドを呼び出す便利な方法を提供し、コンポーネントの再レンダリングをもたらします。多くの場合、アクションはユーザーがボタンをクリックしたことに応答して呼び出されます。Livewire actions[/docs/actions] provide a convenient way to listen to page interactions and invoke a corresponding method on your component, resulting in the re-rendering of the component. Often, actions are invoked in response to the user clicking a button.
Voltを使用してLivewireアクションを定義するには、クロージャを定義するだけです。クロージャを含む変数の名前がアクションの名前を決定します。To define a Livewire action using Volt, you simply need to define a closure. The name of the variable containing the closure will determine the name of the action:
<?php
use function Livewire\Volt\{state};
state(['count' => 0]);
$increment = fn () => $this->count++;
?>
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
クロージャ内では、$this
変数は基になるLivewireコンポーネントにバインドされており、典型的なLivewireコンポーネントで行うのと同じように、コンポーネント上の他のメソッドにアクセスできます。Within the closure, the $this
variable is bound to the underlying Livewire component, giving you the ability to access other methods on the component just as you would in a typical Livewire component:
use function Livewire\Volt\{state};
state(['count' => 0]);
$increment = function () {
$this->dispatch('count-updated');
//
};
アクションは、Laravelのサービスコンテナから引数または依存関係を受け取ることもできます。Your action may also receive arguments or dependencies from Laravel's service container:
use App\Repositories\PostRepository;
use function Livewire\Volt\{state};
state(['postId']);
$delete = function (PostRepository $posts) {
$posts->delete($this->postId);
// ...
};
RenderlessアクションRenderless actions
コンポーネントが、レンダリングされたBladeテンプレートを変更する操作を実行しないアクションを宣言する場合があります。その場合、action
関数内にアクションをカプセル化し、その定義にrenderless
メソッドをチェーンすることで、Livewireのライフサイクルのレンダリングフェーズをスキップできます。In some cases, your component might declare an action that does not perform any operations that would cause the component's rendered Blade template to change. If that's the case, you can skip the rendering phase[/docs/actions#skipping-re-renders] of Livewire's lifecycle by encapsulating the action within the action
function and chaining the renderless
method onto its definition:
use function Livewire\Volt\{action};
$incrementViewCount = action(fn () => $this->viewCount++)->renderless();
保護されたヘルパProtected helpers
デフォルトでは、すべてのVoltアクションは「public」であり、クライアントによって呼び出すことができます。アクション内からのみアクセス可能な関数を作成する場合は、protect
関数を使用できます。By default, all Volt actions are "public" and may be invoked by the client. If you wish to create a function that is only accessible from within your actions[/docs/actions#keep-dangerous-methods-protected-or-private], you may use the protect
function:
use App\Repositories\PostRepository;
use function Livewire\Volt\{protect, state};
state(['postId']);
$delete = function (PostRepository $posts) {
$this->ensurePostCanBeDeleted();
$posts->delete($this->postId);
// ...
};
$ensurePostCanBeDeleted = protect(function () {
// ...
});
フォームForms
Livewireのフォームは、単一のクラス内でフォームの検証と送信を処理する便利な方法を提供します。Voltコンポーネント内でLivewireフォームを使用するには、form
関数を使用できます。Livewire's forms[/docs/forms] provide a convenient way to deal with form validation and submission within a single class. To use a Livewire form within a Volt component, you may utilize the form
function:
<?php
use App\Livewire\Forms\PostForm;
use function Livewire\Volt\{form};
form(PostForm::class);
$save = function () {
$this->form->store();
// ...
};
?>
<form wire:submit="save">
<input type="text" wire:model="form.title">
@error('form.title') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Save</button>
</form>
ご覧のとおり、form
関数はLivewireフォームクラスの名前を受け入れます。定義されると、フォームはコンポーネント内の$this->form
プロパティを介してアクセスできます。As you can see, the form
function accepts the name of a Livewire form class. Once defined, the form can be accessed via the $this->form
property within your component.
フォームに別のプロパティ名を使用する場合は、名前をform
関数の2番目の引数として渡すことができます。If you want to use a different property name for your form, you can pass the name as the second argument to the form
function:
form(PostForm::class, 'postForm');
$save = function () {
$this->postForm->store();
// ...
};
リスナListeners
Livewireのグローバルイベントシステムは、コンポーネント間の通信を可能にします。2つのLivewireコンポーネントがページに存在する場合、イベントとリスナを利用して通信できます。Voltを使用する場合、リスナはon
関数を使用して定義できます。Livewire's global event system[/docs/events] enables communication between components. If two Livewire components exist on a page, they can communicate by utilizing events and listeners. When using Volt, listeners can be defined using the on
function:
use function Livewire\Volt\{on};
on(['eventName' => function () {
//
}]);
認証済みユーザーまたはコンポーネントに渡されたデータに基づいてイベントリスナに動的な名前を割り当てる必要がある場合は、クロージャをon
関数に渡すことができます。このクロージャは、コンポーネントパラメーターだけでなく、Laravelのサービスコンテナを介して解決される追加の依存関係も受け取ることができます。If you need to assign dynamic names to event listeners, such as those based on the authenticated user or data passed to the component, you can pass a closure to the on
function. This closure can receive any component parameter, as well as additional dependencies which will be resolved via Laravel's service container:
on(fn ($post) => [
'event-'.$post->id => function () {
//
}),
]);
便宜上、リスナを定義するときに「ドット」表記を使用してコンポーネントデータを参照することもできます。For convenience, component data may also be referenced when defining listeners using "dot" notation:
on(['event-{post.id}' => function () {
//
}]);
ライフサイクルフックLifecycle hooks
Livewireには、コンポーネントのライフサイクルのさまざまな時点でコードを実行するために使用できるさまざまなライフサイクルフックがあります。Voltの便利なAPIを使用すると、対応する関数を使用してこれらのライフサイクルフックを定義できます。Livewire has a variety of lifecycle hooks[/docs/lifecycle-hooks] that may be used to execute code at various points in a component's lifecycle. Using Volt's convenient API, you can define these lifecycle hooks using their corresponding functions:
use function Livewire\Volt\{boot, booted, ...};
boot(fn () => /* ... */);
booted(fn () => /* ... */);
mount(fn () => /* ... */);
hydrate(fn () => /* ... */);
hydrate(['count' => fn () => /* ... */]);
dehydrate(fn () => /* ... */);
dehydrate(['count' => fn () => /* ... */]);
updating(['count' => fn () => /* ... */]);
updated(['count' => fn () => /* ... */]);
遅延ロードプレースホルダーLazy loading placeholders
Livewireコンポーネントをレンダリングするときに、lazy
パラメーターをLivewireコンポーネントに渡して、最初のページのロードが完了するまでロードを遅延させることができます。デフォルトでは、LivewireはコンポーネントがロードされるDOMに<div></div>
タグを挿入します。When rendering Livewire components, you may pass the lazy
parameter to a Livewire component to defer its loading[/docs/lazy] until the initial page is fully loaded. By default, Livewire inserts <div></div>
tags into the DOM where the component will be loaded.
最初のページのロード中にコンポーネントのプレースホルダーに表示されるHTMLをカスタマイズする場合は、placeholder
関数を使用できます。If you would like to customize the HTML that is displayed within the component's placeholder while the initial page is loaded, you may use the placeholder
function:
use function Livewire\Volt\{placeholder};
placeholder('<div>Loading...</div>');
バリデーションValidation
Livewireは、Laravelの強力なバリデーション機能への簡単なアクセスを提供します。VoltのAPIを使用すると、rules
関数を使用してコンポーネントのバリデーションルールを定義できます。従来のLivewireコンポーネントと同様に、これらのルールはvalidate
メソッドを呼び出すときにコンポーネントデータに適用されます。Livewire offers easy access to Laravel's powerful validation features[/docs/validation]. Using Volt's API, you may define your component's validation rules using the rules
function. Like traditional Livewire components, these rules will be applied to your component data when you invoke the validate
method:
<?php
use function Livewire\Volt\{rules};
rules(['name' => 'required|min:6', 'email' => 'required|email']);
$submit = function () {
$this->validate();
// ...
};
?>
<form wire:submit.prevent="submit">
//
</form>
認証済みユーザーまたはデータベースからの情報に基づくルールなど、ルールを動的に定義する必要がある場合は、クロージャをrules
関数に指定できます。If you need to define rules dynamically, such as rules based on the authenticated user or a information from your database, you can provide a closure to the rules
function:
rules(fn () => [
'name' => ['required', 'min:6'],
'email' => ['required', 'email', 'not_in:'.Auth::user()->email]
]);
エラーメッセージと属性Error messages and attributes
バリデーション中に使用されるバリデーションメッセージまたは属性を変更するには、messages
メソッドとattributes
メソッドをrules
定義にチェーンできます。To modify the validation messages or attributes used during validation, you can chain the messages
and attributes
methods onto your rules
definition:
use function Livewire\Volt\{rules};
rules(['name' => 'required|min:6', 'email' => 'required|email'])
->messages([
'email.required' => 'The :attribute may not be empty.',
'email.email' => 'The :attribute format is invalid.',
])->attributes([
'email' => 'email address',
]);
ファイルアップロードFile uploads
Volt を使用すると、Livewire のおかげで、ファイルのアップロードと保存が非常に簡単になります。機能的な Volt コンポーネントに Livewire\WithFileUploads
トレイトを含めるには、usesFileUploads
関数を使用します。When using Volt, uploading and storing files[/docs/uploads] is much easier thanks to Livewire. To include the Livewire\WithFileUploads
trait on your functional Volt component, you may use the usesFileUploads
function:
use function Livewire\Volt\{state, usesFileUploads};
usesFileUploads();
state(['photo']);
$save = function () {
$this->validate([
'photo' => 'image|max:1024',
]);
$this->photo->store('photos');
};
URL クエリパラメータURL query parameters
コンポーネントの状態が変化したときに、ブラウザの URL クエリパラメータを更新すると便利な場合があります。このような場合、url
メソッドを使用すると、Livewire に URL クエリパラメータをコンポーネントの状態と同期させるように指示できます。Sometimes it's useful to update the browser's URL query parameters[/docs/url] when your component state changes. In these cases, you can use the url
method to instruct Livewire to sync the URL query parameters with a piece of component state:
<?php
use App\Models\Post;
use function Livewire\Volt\{computed, state};
state(['search'])->url();
$posts = computed(function () {
return Post::where('title', 'like', '%'.$this->search.'%')->get();
});
?>
<div>
<input wire:model.live="search" type="search" placeholder="Search posts by title...">
<h1>検索結果:</h1>
<ul>
@foreach($this->posts as $post)
<li wire:key="{{ $post->id }}">{{ $post->title }}</li>
@endforeach
</ul>
</div>
Livewire でサポートされている追加の URL クエリパラメータオプション (URL クエリパラメータのエイリアスなど) は、url
メソッドに提供することもできます。Additional URL query parameters options supported by Livewire, such as URL query parameters aliases, may also be provided to the url
method:
use App\Models\Post;
use function Livewire\Volt\{state};
state(['page' => 1])->url(as: 'p', history: true, keep: true);
// ...
ページネーションPagination
Livewire と Volt は、ページネーションも完全にサポートしています。機能的な Volt コンポーネントに Livewire の Livewire\WithPagination
トレイトを含めるには、usesPagination
関数を使用します。Livewire and Volt also have complete support for pagination[/docs/pagination]. To include Livewire's Livewire\WithPagination
trait on your functional Volt component, you may use the usesPagination
function:
<?php
use function Livewire\Volt\{with, usesPagination};
usesPagination();
with(fn () => ['posts' => Post::paginate(10)]);
?>
<div>
@foreach ($posts as $post)
//
@endforeach
{{ $posts->links() }}
</div>
Laravel と同様に、Livewire のデフォルトのページネーションビューでは、スタイル設定に Tailwind クラスが使用されます。アプリケーションで Bootstrap を使用している場合は、usesPagination
関数を呼び出すときに目的のテーマを指定して、Bootstrap ページネーションテーマを有効にできます。Like Laravel, Livewire's default pagination view uses Tailwind classes for styling. If you use Bootstrap in your application, you can enable the Bootstrap pagination theme by specifying your desired theme when invoking the usesPagination
function:
usesPagination(theme: 'bootstrap');
カスタムトレイトとインターフェースCustom traits and interfaces
機能的な Volt コンポーネントに任意のトレイトまたはインターフェースを含めるには、uses
関数を使用します。To include any arbitrary trait or interface on your functional Volt component, you may use the uses
function:
use function Livewire\Volt\{uses};
use App\Contracts\Sorting;
use App\Concerns\WithSorting;
uses([Sorting::class, WithSorting::class]);
匿名コンポーネントAnonymous components
ページの一部を、別のファイルに抽出せずに Volt コンポーネントに変換したい場合があります。たとえば、次のビューを返す Laravel ルートを想像してください。Sometimes, you may want to convert a small portion of a page into a Volt component without extracting it into a separate file. For example, imagine a Laravel route that returns the following view:
Route::get('/counter', fn () => view('pages/counter.blade.php'));
ビューの内容は、レイアウト定義やスロットなどを含む、典型的な Blade テンプレートです。ただし、ビューの一部を @volt
Blade ディレクティブで囲むことで、ビューの一部を完全に機能する Volt コンポーネントに変換できます。The view's content is a typical Blade template, including layout definitions and slots. However, by wrapping a portion of the view within the @volt
Blade directive, we can convert that piece of the view into a fully-functional Volt component:
<?php
use function Livewire\Volt\{state};
state(['count' => 0]);
$increment = fn () => $this->count++;
?>
<x-app-layout>
<x-slot name="header">
Counter
</x-slot>
@volt('counter')
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
@endvolt
</x-app-layout>
匿名コンポーネントへのデータの受け渡しPassing data to anonymous components
匿名コンポーネントを含むビューをレンダリングする場合、ビューに渡されたすべてのデータは、匿名 Volt コンポーネントでも利用できます。When rendering a view that contains an anonymous component, all of the data given to the view will also be available to the anonymous Volt component:
use App\Models\User;
Route::get('/counter', fn () => view('users.counter', [
'count' => User::count(),
]));
もちろん、このデータを Volt コンポーネントで "state" として宣言することもできます。ビューによってコンポーネントにプロキシされたデータから state を初期化する場合は、state 変数の名前を宣言するだけで済みます。Volt は、プロキシされたビューデータを使用して state のデフォルト値を自動的にハイドレートします。Of course, you may declare this data as "state" on your Volt component. When initializing state from data proxied to the component by the view, you only need to declare the name of the state variable. Volt will automatically hydrate the state's default value using the proxied view data:
<?php
use function Livewire\Volt\{state};
state('count');
$increment = function () {
// 新しいカウント値をデータベースに保存...
$this->count++;
};
?>
<x-app-layout>
<x-slot name="header">
Initial value: {{ $count }}
</x-slot>
@volt('counter')
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
</div>
@endvolt
</x-app-layout>
コンポーネントのテストTesting components
Volt コンポーネントのテストを開始するには、コンポーネントの名前を指定して、Volt::test
メソッドを呼び出します。To begin testing a Volt component, you may invoke the Volt::test
method, providing the name of the component:
use Livewire\Volt\Volt;
it('increments the counter', function () {
Volt::test('counter')
->assertSee('0')
->call('increment')
->assertSee('1');
});
Volt コンポーネントをテストするときは、標準の Livewire テスト API で提供されるすべてのメソッドを利用できます。When testing a Volt component, you may utilize all of the methods provided by the standard Livewire testing API[/docs/testing].
Volt コンポーネントがネストされている場合は、「ドット」表記を使用して、テストするコンポーネントを指定できます。If your Volt component is nested, you may use "dot" notation to specify the component that you wish to test:
Volt::test('users.stats')
匿名 Volt コンポーネントを含むページをテストする場合は、assertSeeVolt
メソッドを使用して、コンポーネントがレンダリングされていることをアサートできます。When testing a page that contains an anonymous Volt component, you may use the assertSeeVolt
method to assert that the component is rendered:
$this->get('/users')
->assertSeeVolt('stats');