In this article we will learn how to use Sweetalert in vue.js.
Sweetalert:
Sweetalert use to show the user information like success, warning, error, etc.
Step 1: Create new Vue.js project:
vue create sweetalert-demo
Step 2: Install require packages:
npm i bootstrap bootstrap-vue vue-sweetalert2
Step 3: Open main.js file and add the following in it:
import Vue from "vue"; import App from "./App.vue"; import VueSweetalert2 from "vue-sweetalert2"; import { BootstrapVue } from "bootstrap-vue"; import "sweetalert2/dist/sweetalert2.min.css"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap-vue/dist/bootstrap-vue.css"; Vue.use(VueSweetalert2); Vue.use(BootstrapVue); Vue.config.productionTip = false; new Vue({ render: (h) => h(App), }).$mount("#app");
Step 4: Create SweetAlert.vue file and add the following in it:
<template> <div class="row mx-auto justify-content-center"> <button class="btn btn-outline-primary col-1 p-2 m-2" @click="showAlert"> Simple </button> <button class="btn btn-outline-success col-1 p-2 m-2" @click="showSuccessAlert" > Success </button> <button class="btn btn-outline-danger col-1 p-2 m-2" @click="showErrorAlert" > Error </button> <button class="btn btn-outline-warning col-1 p-2 m-2" @click="showWarningAlert" > Warning </button> <button class="btn btn-outline-info col-1 p-2 m-2" @click="showInfoAlert"> Info </button> <button class="btn btn-outline-secondary col-1 p-2 m-2" @click="showMultipleButtonAlert" > With multiple buttons </button> <button class="btn btn-outline-dark col-1 p-2 m-2" @click="showToast"> Toast </button> </div> </template> <script> export default { name: "SweetAlert", methods: { showAlert() { this.$swal("Hello Vue world!!!"); }, showSuccessAlert() { this.$swal("Success", "Success alert!", "success"); }, showErrorAlert() { this.$swal("Oops...", "Something went wrong!", "error"); }, showWarningAlert() { this.$swal("Warning", "Warning alert!!", "warning"); }, showInfoAlert() { this.$swal("Info", "Info alert!!", "info"); }, showMultipleButtonAlert() { this.$swal({ title: "Do you want to save the changes?", showDenyButton: true, showCancelButton: true, confirmButtonText: "Save", denyButtonText: `Don't save`, }); }, showToast() { this.$swal({ toast: true, icon: "success", title: "Posted successfully", animation: true, position: "top-end", showConfirmButton: true, }); }, }, }; </script>
Step 5: Open App.vue file and add the following in it:
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png" /> <h2>Vue-Sweetalert2 Demo</h2> <SweetAlert /> </div> </template> <script> import SweetAlert from "./components/SweetAlert.vue"; export default { name: "App", components: { SweetAlert, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Code in action: