Synchronization Strategy
To achieve seamless two-way synchronization between Alpine.js and Laravel Livewire, use the entangle method for property binding and the wire:ignore directive to prevent DOM-related resets during server-side re-renders.
Recommended Pattern for Embedding
The most robust pattern is to wrap Alpine-driven elements within Livewire components, using x-data to initialize Alpine variables from Livewire properties. This ensures that when Alpine updates the state, Livewire is notified, and vice versa.
<div wire:ignore x-data=""search: $wire.entangle('"query"')">
<input type="text" x-model=""search"">
<span x-text=""search"">/span>
</div>
Maintaining State with wire:ignore and $dispatch
The wire:ignore directive tells Livewire to skip that specific DOM element during its update cycle. This is critical when Alpine manages complex UI state (like open toggles or temporary input values) that the server does not need to track. To send data back to the server without losing local state:
- Use
wire:ignore on the parent container of your Alpine component.
- Use Alpine's
$dispatch to fire custom browser events that Livewire can listen for.
- Listen for these events in Livewire using the
wire:on.event-name listener attribute to trigger server-side logic.
Version-Specific Pitfalls (Alpine 3 & Livewire 3)
In Livewire 3, the $wire object is globally available within Alpine components, simplifying access to component methods. However, be aware of these:
- Entangle Timing: By default,
entangle synchronizes on every change. Use $wire.entangle('prop', { defer: true }) to delay synchronization until a specific action is triggered, significantly reducing overhead.
- Morphing: Livewire 3 uses a more aggressive DOM morphing strategy. If Alpine components are not wrapped in
wire:ignore, morphing might reset the internal Alpine state if the HTML structure changes on the server.
- Syntax: Ensure you are using the
$wire.property syntax rather than the older $this.$wire to maintain compatibility with the latest reactive features.
Note: Are you experiencing the state loss specifically on every keystroke, or only after a server-side validation trigger?