1

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 ()

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

13 Comments

I did that, it didn't work either, the variable is generated after clicking, maybe it receives the value in the javascript but it doesn't update it
Is the script part of the blade file? If so, it should update. Also, your render method returns view('livewire.counter'); while the file was named resorces/views/livewire/data.blade.php. Is this just a typo?
Yes, it's in the same blade file and it is a typo.
Can you see inspect the content on your site to see if the variable is printed out after var data = ...?
Im thinking that I must create a listener, when the url parameters change... Get the information
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.