andcl
andcl

Reputation: 3558

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

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.

Upvotes: 2

Views: 6426

Answers (2)

morethanctrlc
morethanctrlc

Reputation: 41

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>

Upvotes: 4

Yolan Mees
Yolan Mees

Reputation: 107

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.

Upvotes: 0

Related Questions