Search code examples
laravellaravel-livewirealpine.js

Alpine.js - Passing javascript variable to Livewire


I have a simple Livewire component called index.blade.php. All it does currently is render below:

<div x-data>
    <div x-text="JSON.stringify($store.data.entities)"></div>
</div>

The data above comes from my app.js file:

Alpine.store('data', {
    entities: [{'type': 'order', 'reference': '12345678'}],
})

Thus in my component, the following will be rendered:

[{"type":"order","reference":"12345678"}]

This works fine. However, I want to pass the value of $store.data.entities to another Livewire component:

<div x-data>
    <div x-text="JSON.stringify($store.data.entities)"></div>
    <!-- Show specific entity -->
    @livewire('show-entity', [])
</div>

However, I am not sure how I can pass the $store.data.entities as a parameter to show-entity component?


Solution

  • If you are using Livewire 2 or above, you can use $wire.

    Move the div inside your Livewire component, then simply:

    <div x-data="{'entities': JSON.stringify($store.data.entities)}" x-text="entities" x-init="$wire.set('entities', entities')"></div>
    

    Upon init of Alpine, it should set the Livewire variable (called $entities in this example) to the value of your JSON.