Joseph
Joseph

Reputation: 126

How do I to receive a variable from Livewire in a Javascript script?

I have a Livewire Component in app/Http/Livewire/Data.php

class Data extends Component
{
    public $data= 0;

    public function data()
    {
        $this->data= 100;
    }

    public function render()
    {
        return view('livewire.data');
    }
}

I have a view in resorces/views/livewire/data.blade.php I want to know how I can make use of the $data variable within a script found in this same view.

<div style="text-align: center">
    <button wire:click="data"> My buttom</button>
    <-- Here its shown without problems -->
    <h1>{{ $data }}</h1>
</div>

<!-- Not shown here -->
<script>
    document.addEventListener('livewire:load', function () {
        var data = @this.data
        console.log(data) 
    })
</script>

It doesn't show me the value of data when I doing console.log ()

Upvotes: 1

Views: 3893

Answers (1)

spekulatius
spekulatius

Reputation: 1499

Within your Blade file, you can simply set the variable in JavaScript:

<div style="text-align: center">
    <button wire:click="data"> My buttom</button>
    <-- Here its shown without problems -->
    <h1>{{ $data }}</h1>
</div>

<!-- Not shown here -->
<script>
var data = {{ $data }}
console.log(data) 
</script>

Upvotes: 1

Related Questions