The alert() method available on the Window object for notifications and alerts in your apps is really not ideal for most situations. For one, it’s ugly and has no way to be customized. Thankfully, a popular library called SweetAlert 2 (sucessor to SweetAlert) offers us a great replacement that’s responsive, customizable and accessible.
vue-sweetalert2 is a wrapper for SweetAlert 2 that makes it easy to integrate the capabilities in your Vue apps.
Here’s we’ll go over the basic setup and usage.
Install vue-sweetalert in your Vue.js project using npm or Yarn:
With the package installed, all you’ll need is to add the VueSweetalert2 component to your main.js
file:
Now in the main app you can access all the methods of Vue-Sweetalert2 using the $swal function:
SweetAlert 2 comes with other built-in methods which we’ll explore in this section. You can also refer to the API documentation for more examples.
If you want a modal/popup that can accept user input, simply use the input key in the configuration passed to $swal:
You can also add your own markup as part of the modal. Simply use the html key in the configuration:
SweetAlert 2 uses promises to keep track of how a user interact with the notification. In the following example, we display a success prompt if the promise resolves with a truthy value, and otherwise we display another alert prompt displaying an alternative message:
There you go! 🚀 That was really fast and easy-enough right? You can now create simple and easy alerts and notifications in your apps with just a few lines of code.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
How can i change the title and text color please ? Thank you