Getting Error: Uncaught (in promise) ReferenceError: livewire is not defined

147 Views Asked by At

I am trying to call wire:click="deleteImage(1)" through jquery -

livewire.emit('deleteImage', 1);

but getting an error - Uncaught (in promise) ReferenceError: livewire is not defined

1

There are 1 best solutions below

6
Pippo On BEST ANSWER

You must ensure that livewire has been initialized.
Also emit is a 2.0 method to dispatch events, it can't be used directly to call methods.

Here a simplified working example:

<?php
//class App\Livewire\JQry

namespace App\Livewire;

use Livewire\Component;

class JQry extends Component
{
    public $test = 1;


    public function add()
    {
        $this->test++;
    }
}

{{-- resources/views/livewire/j-qry.blade.php --}}

<div>

    <button id="but1">
        [Add 1]
    </button>

    <br>

    {{ $test }}


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>

    document.addEventListener("livewire:init", () => {

            $("#but1").on ("click", () => {

                // add() is an example method from the Livewire class - in your case you will call deleteImage(1)
                window.Livewire.getByName("j-qry")[0].add();

                // @this.add(); ---> if the script is set in the template we can use this shorthand format

            });
    });

</script>

</div>