Alpine
-
Controlling Livewire from Alpine using
$wire
-
Sharing state using
$wire.entangle
- Alpine Arrow Function Syntax and Object Literal Notation
- Additional Resources
$wire
Controlling Livewire from Alpine using $wire
is a magic object representing the Livewire component, all properties from your component
can be accessed or mutated straight from JavaScript.
Character count: <span x-text="$wire.content.length"></span>
Mutating Livewire properties
<button type="button" x-on:click="$wire.title = ''">Clear</button>
Calling Livewire methods
In the following example, Alpine will listen or an blur event triggering a form save.
<form wire:submit="save">
<input wire:model="title" type="text" x-on:blur="$wire.save()">
<button type="submit">Save</button>
</form>
Refreshing a component
You can easily refresh a Livewire component (trigger network roundtrip to re-render a component's
Blade view) using $wire.$refresh()
:
<button type="button" x-on:click="$wire.$refresh()">
$wire.entangle
Sharing state using You can share state between Livewire and Alpine using $wire.entangle
:
This is particularly useful utility that can be used to keep values from Livewire in-sync with values in Alpine.
Alpine Arrow Function Syntax and Object Literal Notation
Arrow Function with Implicit Return
Use this when you want to return an object directly without any additional logic.
Alpine.data('simpleComponent', () => ({
title: 'Hello World',
show() {
console.log(this.title);
}
}));
When to use:
- When you want to return an object directly without any additional logic.
- When you want to keep the code clean and concise.
- When you want to avoid using the
return
keyword.
When not to use:
- When you need to perform additional logic before returning an object.
- When the object should not directly expose all variables.
- When you need to use local variables.
Arrow Function with Explicit Return and Local Variables
Use this when you need to perform additional logic before returning an object or when the object should not directly expose all variables.
Alpine.data('complexComponent', () => {
let title = 'Hello World';
let count = 0;
function increment() {
count += 1;
console.log(count);
}
return {
title: title,
show() {
console.log(this.title);
},
increment: increment
};
});
When to use:
- When you need to perform additional logic before returning an object.
- When the object should not directly expose all variables.
- When you need to use local variables.
When not to use:
- When you want to return an object directly without any additional logic.
- When you want to keep the code clean and concise.
<input type="text" x-model="$wire.entangle('title')">