how to use sweet alert in vue js

Using Sweet Alert in Vue.js

To use Sweet Alert in Vue.js, you can follow these steps:

  1. Install Sweet Alert: First, you need to install the Sweet Alert package using npm or yarn. Open your terminal and run the following command:

npm install sweetalert2

or

yarn add sweetalert2

  1. Import Sweet Alert: In your Vue component, import Sweet Alert using the import statement. You can import it globally in your main.js file or import it locally in a specific component.

javascript import Swal from 'sweetalert2'

  1. Use Sweet Alert: Once Sweet Alert is imported, you can use it to display alerts, confirmations, prompts, and more. Here's an example of displaying a basic alert:

javascript Swal.fire('Hello!', 'This is a Sweet Alert!', 'success')

In this example, Swal.fire() is used to display an alert with the title "Hello!", the message "This is a Sweet Alert!", and a success icon.

You can customize the alert by passing different options to the Swal.fire() function. For example, you can change the icon, add buttons, and handle user actions. Refer to the Sweet Alert documentation for more customization options and examples.

  1. Handling User Actions: Sweet Alert provides various methods to handle user actions, such as clicking buttons or closing the alert. You can use promises or async/await syntax to handle these actions. Here's an example of handling a user's confirmation:

javascript Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.isConfirmed) { // User confirmed, perform delete operation Swal.fire('Deleted!', 'Your file has been deleted.', 'success') } else if (result.dismiss === Swal.DismissReason.cancel) { // User clicked cancel, do nothing Swal.fire('Cancelled', 'Your file is safe :)', 'error') } })

In this example, Swal.fire() is used to display a confirmation dialog with a title, text, and buttons. The then() method is used to handle the user's choice. If the user confirms the action, a success message is displayed. If the user cancels the action, an error message is displayed.

That's it! You have now successfully integrated Sweet Alert into your Vue.js application. You can explore more features and customization options provided by Sweet Alert in the official documentation.

Note: Make sure to import Sweet Alert correctly and refer to the official documentation for the latest usage instructions and options.