Livewire + AlpineJS: Using x-data as wire:click param

4.9k views Asked by At

I have a Laravel Blade template which has an AlpineJS div defined like this:

<div x-data="{ id: 2 }">
   ...
   <button type="button" wire:click="deleteAddress(id)">Button</button>
</div>

What I want is somehow "pass" that id variable to the wire:click call.

The above code throws an Uncaught ReferenceError: id is not defined in my JS console. Any ideas? Just starting with the TALL stack and I do not know the optimal workflows yet.

Thanks in advance.

2

There are 2 answers

0
Yolan Mees On

Add a wire:key to the same div as the x-data.

<div wire:key="id" x-data="{ id: 2 }">
   ...
   <button type="button" wire:click="deleteAddress(id)">Button</button>
</div>

I think this is because Livewire only updates what is changing. And the x-data div is the top div of an alpine component. so if you add the id as wire:key to the div that contains the x-data then this div will also get updated and it will rerun the alpine component.

1
morethanctrlc On

You could use Alpine click listener with the magic $wire, as described here: https://laravel-livewire.com/docs/2.x/alpine-js

This way you'll stay "inside" Alpine, but with access to your Livewire component method. So it's going to be:

<div x-data="{ id: 2 }">
   ...
   <button type="button" @click="$wire.deleteAddress(id)">Button</button>
</div>