Livewire + AlpineJS
Hi, im currently learning laravel framework along with livewire. I also utilized AlpineJS for some specific client-side logic. I want to ask if the following code is considered to be best practice, and also a question at the end
I have a full-page livewire component like the following:
TestComponent.php
<?php
namespace App\Livewire;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.base')]
class TestComponent extends Component
{
public $bootCount = 0;
public $message = 'message - livewire';
public function boot()
{
$this->bootCount++;
}
public function render()
{
return view('livewire.test-component');
}
public function doSomethingWire()
{
if ($this->bootCount % 2 === 0) {
$this->message = 'bootCount is even';
} else {
$this->message = 'bootCount is odd';
}
}
}
and the test-component.blade.php
<div>
<div x-data="testComponent">
<button @click="$wire.doSomethingWire">doSomethingWire</button>
<button @click="doSomethingAlpine">doSomethingAlpine</button>
<span x-text="$wire.message"></span>
<span x-text="$wire.bootCount"></span>
</div>
</div>
@script
<script>
document.addEventListener('livewire:initialized', () => {
console.log('here');
});
Alpine.data('testComponent', () => {
return {
doSomethingAlpine() {
console.log($wire.message);
}
}
});
</script>
@endscript
this simple full-page component works just fine, however there's something im confused with. So, when i navigate to another page (using a wire:navigate of course in my navbar layout), and i clicked on the browser's client back button (the <- arrow), AlpineJS suddently not working, especially on the 'doSomethingAlpine' method. It throws an error like the following:
Alpine Expression Error: undefined
Expression: "doSomethingAlpine"
I've tried experimenting on it by replacing the $wire.message inside that method into a simple string, and it worked. Currently, i can only narrow the problem down to the $wire.message part, anyone else's thoughts on this ?
Please or to participate in this conversation.