ChrisDLH
ChrisDLH

Reputation: 133

open modal automatically in livewire component it doesn't work

I wanna show a modal when initializing the component, but it doesn't work. I'm using $this->emit('show) to open the modal

When I add a button in my view the emit('show') works!, but I don't want that, what I want is that when the view is loaded, the modal is automatically shown

this is my component:

public function mount($id)
{
    if ($id != null) {
        try {
            $data = DetalleRamComputadora::find($id);
            $this->fk_ram_tecnologia    = $data->fk_tecnologia;
            $this->fk_ram_capacidad     = $data->fk_capacidad;
            $this->fk_ram_frecuencia    = $data->frecuencia;

            $this->emit('show'); // Close modal "create"
        } catch (\Throwable $th) {
            // throw $th;
        }
    }
}

this is my script on my view;

<script type="text/javascript">

    window.livewire.on('show', () => {
         $('#exampleModal').modal('show');
    });
    
</script>

and this is my modal:

<div wire:ignore.self class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" >
                 <span aria-hidden="true close-btn">×</span>
            </button>
        </div>
        <div class="modal-body">
            ...
        </div>
        <div class="modal-footer">
            ...
        </div>
    </div>
</div>

Upvotes: 0

Views: 9464

Answers (1)

Genivaldo Silva
Genivaldo Silva

Reputation: 56

The emit occurs before the DOM is complete, so your script is not executed.

Suggestion:

wire:init="openModal"

in

<div wire:init="openModal" wire:ignore.self class="modal fade" id="exampleModal"...

And in the component:

 public function openModal()
 {
     $this->emit('show');
 }

Or

You can try:

<script>
    $(document).ready(function () {
        window.livewire.emit('show');
    });

    window.livewire.on('show', () => {
        $('#exampleModal').modal('show');
    });
</script>

More simple!

Upvotes: 4

Related Questions