Interacting with components in Alpine JS
Since Livewire and Alpine.js where both developed by Caleb Porzio, they often are used together and facilities exist to make this easy.
Getting components in Alpine.js
A $wire
property is automatically made available on Alpine.js components within a Magewire component.
This $wire
property represents the Magewire component, and can be used to interact with the PHP component properties and methods.
Reading properties in Alpine.js
Component properties can be accessed using the $wire.get()
method.
Writing properties in Alpine.js
Any Magewire properties can be set on $wire
using either the direct assignment or the set()
method:
Linking Magewire and Alpine component properties
Magewire allows linking the value of an Alpine component property inside a Magewire component to a property of the Magewire component.
Whenever one is updated, the other is updated at the same time automatically.
This feature is called entanglement
, and is enabled by the $wire.entangle()
method.
The $wire.entangle()
method has to be called individually for each property to be linked.
For example, imagine we have this simple component with only a single property $foo
.
The following template code shows different ways to update the component value:
<div x-data="{ foo: $wire.entangle('foo') }">
<!-- Mutate the "entangled" property foo using Alpine: -->
<button type="button" class="btn" @click="foo = foo + 1">Inc +1</button>
<!-- Mutate the "entangled" property foo using the magic Alpine property $wire: -->
<button type="button" class="btn" @click="$wire.foo = foo + 2">Inc +2</button>
<!-- Mutate the "entangled" property foo using Magewire: -->
<button type="button" class="btn" wire:click="$set('foo', 0)">Reset</button>
<div>Client side rendered: <span x-text="foo"></span></div>
<div>Server side rendered: <?= /** @noEscape */ $magewire->foo ?></div>
</div>
If you try out the above example, you will see the client-side rendered value update immediately when the "Inc +1" button is clicked, followed shortly after by the server-side rendered value when the Magewire Ajax request completes.
The other two buttons use Magewire to mutate the property, so both the values on the screen are updated at the same instant once the Magewire Ajax roundtrip completes.
Calling methods from Alpine.js
Magewire component methods can be triggered by calling them directly on $wire
or by passing the method name to call()
.
<!-- call the "track" method of the component on every non-captured click (do not do this for real) -->
<div x-data="" @click.window="$wire.track(Date.now())">
<div>...other content ...</div>
<div @touchstart="$wire.call('interaction', $event.target.dataset.id)" data-id="foo">
...even more content...
</div>
</div>
All method calls on a Magewire component return a promise that resolves when the subsequent roundtrip completes.
However, it does not resolve to a meaningful value; the return value of the PHP method is ignored.