Skip to main content
  1. About
  2. For Teams
Asked
Modified today
Viewed 29 times
1

I'm using Laravel 12 and Livewire 3, and now I'm trying to use sweetalert2 in component file.

Here is what I've already done:

  1. install sweetalert2 : npm install sweetalert2
  2. in resources\js\app.js :
import Swal from "sweetalert2"; 
window.Swal = Swal;
  1. in blade file :
@script
<script>
    window.addEventListener('swal-alert',function(e){
        Swal.fire(e.detail);
    });
</script>
@endscript
  1. in component file when wire:click in the button executed :
$this->dispatch('swal-alert', [
    'type' => 'success',
    'title' => 'Success!',
    'text' => 'Operation completed successfully.'
]);

In the blade file I have also added the following button:

<button wire:loading class="btn btn-info">
   Loading...
 </button>

This button is being shown, however sweetalert2 isn't. What could be the issue that that sweetalert2 isn't visible?

1 Answer 1

0

Try changing your event listener to use Livewire.on() instead of window.addEventListener(), since Livewire dispatches events through its own system.
Example:

<script>
    document.addEventListener('livewire:init', () => {
        Livewire.on('swal-alert', e => {
            Swal.fire(e);
        });
    });
</script>

And make sure your dispatch call is:

$this->dispatch('swal-alert', [
    'icon' => 'success',
    'title' => 'Success!',
    'text' => 'Operation completed successfully.'
]);

(typeicon is the correct key for SweetAlert2.)

New contributor
Hossein Hezami is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Post as a guest

Required, but never shown

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.