To maintain client-side state with Livewire without using Alpine.js, you can leverage Livewire's wire:ignore directive. This directive tells Livewire to ignore a specific part of the DOM when it performs updates, which can help preserve the state of elements that are managed by vanilla JavaScript or other means.
Here's how you can modify your code to use wire:ignore for the elements that you want to preserve the state for:
<?php
use function Livewire\Volt\{state};
state(['nb' => 0]);
$plus = fn() => $this->nb++;
$minus = fn() => $this->nb--;
?>
<div x-init="console.log('Im initing')" x-data="{nb: $wire.nb}" class="box">
<div class="notification title">
{{ $nb }} - <span x-text="nb"></span> - <span id="mynb">{{ $nb }}</span>
</div>
<details open class="box" wire:ignore>
<summary class="is-clickable is-unselectable">Accordion 1</summary>
<p>
hello paris
</p>
<input type="text">
</details>
<div class="buttons" wire:ignore>
<button type="button" class="button" onclick="mynb.innerText--">
minus vanilla
</button>
<button type="button" class="button" onclick="mynb.innerText++">
plus vanilla
</button>
</div>
<div class="buttons">
<button type="button" class="button" x-on:click="nb--">
minus alpine
</button>
<button type="button" class="button" x-on:click="nb++">
plus alpine
</button>
</div>
<div class="buttons">
<button type="button" class="button" wire:click="minus">
minus
</button>
<button type="button" class="button" wire:click="plus">
plus
</button>
</div>
</div>
Explanation:
-
wire:ignoreDirective: By addingwire:ignoreto thedetailsandbuttonselements that are managed by vanilla JavaScript, Livewire will not re-render these parts of the DOM. This helps in preserving their state across Livewire updates. -
Alpine.js Elements: The elements managed by Alpine.js do not need
wire:ignorebecause Alpine.js integrates well with Livewire and preserves its state automatically. -
Vanilla JavaScript Elements: The
wire:ignoredirective is particularly useful for elements managed by vanilla JavaScript, as it prevents Livewire from resetting their state.
This approach should help you maintain the client-side state for elements that are not directly tied to Livewire or Alpine.js.