Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sAnsic's avatar

$wire in Alpine.data()

How to access the Livewire component from the method declared in Alpine.data() (similar to the $wire magic method)

You need to move the method call from

<div x-data>
    <button @click="$wire.showModal().then( () => console.log('OK') )"</button>
</div>

to

<div x-data="modals">
    <button @click="showModal()"</button>
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('modals', () => ({
        showModal() {
            $wire.showModal().then( () => console.log('OK') ) // $wire is not defined
        }
    }))
})
</script>
  • This is an example to understand what is needed
0 likes
5 replies
StefanSchmalhaus's avatar

I have the same problem. I also want to use $wire inside Alpine.data(). I tried wrapping the JavaScript part inside @script/@endscript directives. But that doesn't work either. Have you found a solution in the meantime?

leyduana's avatar

You need to pass the $wire object explicitly to Alpine.data.

<div x-data="modals($wire)">
    <button @click="showModal()"</button>
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('modals', ($wire) => ({
        showModal() {
            $wire.showModal().then( () => console.log('OK') ) // $wire is not defined
        }
    }))
})
</script>
Chingy's avatar

I always do

@script 
	<script>
		Alpine.data('myFunction', () => {
			return {
				// The stuff
			}
		})
	</script>
@endscript

I dont add it behind any alpine:init or livewire:init/initialized and works perfectly

sAnsic's avatar
Level 1

@this.showModal().then( () => console.log('OK') )

this.$wire.showModal().then( () => console.log('OK') )

Chingy's avatar

@sAnsic in Alpine function context, this.$wire, or $wire is the same.

@this, is deprecated since LW3

1 like

Please or to participate in this conversation.