Tuesday, October 9, 2018

Vuejs Sweetalert.js - Beautiful popup or alert notifications with examples

In this blog post, We are going to learn How to create a popup in a vuejs application using the sweetalert framework

I already blogged about Sweetalert tutorials with examples and Alert Notifications with Angular here as follows

VueJS Alert Component

Alert is  a simple popup dialog box to give useful information to the user
Vuejs is a popular progressive javascript framework for creating single page applications.
Sweetalert is a vanilla opensource lightweight javascript to create a popup notification in javascript applications. The applications can be Jquery, Plain Javascript or NPM based applications like ANgular, Vuejs, and Reactjs

With sweetheart, We can achieve the following alert notifications
  • Alert notifications to give success, warning, error and informational message
  • Popup to Prompt the user to take input information
  • Confirmation alert
  • Responsive 
There are a lot of Vuejs plugin wrappers for providing sweetalert 
In this blog post, We are going to integrate vue-sweetalert2 in vuejs based applications.
This blog post covers two parts
  1. Vuejs Application Creation using vue cli tool
  2. Integrate Sweetalert in Vuejs Application with examples

Vuejs Hello World Application generation

Vue framework provides vue-cli tool to create vue application from scratch using vue create command. 
B:\>vue create vuesweetalertdemo

Vue CLI v3.0.0-rc.8
? Please pick a preset: default (babel, eslint)

Vue CLI v3.0.0-rc.8
✨  Creating project in B:\Workspace\blog\vuesweetalertdemo.
⚙  Installing CLI plugins. This might take a while...

> yorkie@2.0.0 install B:\Workspace\blog\vuesweetalertdemo\node_modules\yorkie
> node bin/install.js

setting up Git hooks
can't find .git directory, skipping Git hooks installation
added 1281 packages in 278.557s
�  Invoking generators...
�  Installing additional dependencies...

added 3 packages in 18.413s
⚓  Running completion hooks...

�  Generating README.md...

�  Successfully created project vuesweetalertdemo.
�  Get started with the following commands:

 $ cd vuesweetalertdemo
 $ npm run serve
This will have vuesweetalertdemo application created with predefined vue folder structure with the initial configuration. Go to the application folder, run npm run serve command to start vue js application.

Install and save Dependencies to application

To integrate SweetalertJS in VueApplicaiton, Go to the application root folder, vue-sweetalert2 package can be installed using npm or yarn or bower.


npm install -save vue-sweetalert2
or 
bower install vue-sweetalert2
or 
yarn add vue-sweetalert2
This command will do the following things
  • Install vue-sweetalert2 in your application and creates folder node_modules\vue-sweetalert2 in application root folder 
  • Added below entry in package.json
  "dependencies": {
 -----
    "vue-sweetalert2": "^1.5.5"
  },

Import VueSweetalert2 module in vue application.

To make use of third-party npm package functionality, FIrst, you need to import VueSweetalert2 module in main.js. Once imported, Application is able to access sweetalert objects and its methods.
main.js
import Vue from 'vue'
import App from './App.vue'
import VueSweetalert2 from 'vue-sweetalert2';
Vue.use(VueSweetalert2);

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Popup Simple alert Example 

This examples application has one button, on clicking the button, It shows an alert box with a simple ok button. App.vue
<template>
  <div id="app">
   <div> <img alt="Vue logo" src="./assets/logo.png"></div>
    <button v-on:click="displaySimplePopup">Click Me</button>
  </div>
</template>

<script>
  export default {
    data() {
        return {
          msg:''
        };
    },
    methods: {
        displaySimplePopup(){
            // Use Sweetalert
            this.$swal('Welcome to Vuejs Application using 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>
And the output of the above code is
vue sweetalert examples  popup notification

Modal Examples 

This Below demo covers the following things
  • How to display a successful dialog window? 
  • How to show informational dialog window? 
  • How to display Error dialog window? 
  • Modal window Prompt to take input from the user 
  • Alert display position change 
  • Delete popup notification
<template>
  <div id="app">
   <div> <img alt="Vue logo" src="./assets/logo.png"></div>
    <button v-on:click="displaySimplePopup">Click Me</button>
    <button v-on:click="infoAlert">Info Popup</button>
    <button v-on:click="successAlert">Success Popup</button>
    <button v-on:click="errorAlert">Error Popup</button>
    <button v-on:click="AlertPassingData">Prompt Popup</button>
    <button v-on:click="positionPopup">Custom Position Popup</button>
    <button v-on:click="deletePopup">Delete Popup</button>
  </div>
</template>

<script>
  export default {
    data() {
        return {
          msg:''
        };
    },
    methods: {
        displaySimplePopup(){
            // Use Sweetalert
            this.$swal('Welcome to Vuejs Application using Sweetalert');
        },
        infoAlert() {
            this.$swal({
                type: 'info',
                title: 'Title Info',
                text: 'This is informational message'
            });
        },
        successAlert() {
            this.$swal({
                type: 'success',
                title: 'Title Success',
                text: 'This is successful message'
            });
        },
        errorAlert() {
            this.$swal({
                type: 'error',
                title: 'Error Title ...',
                text: 'Error Occured!',
                footer: '<a href>Please click this for more about this error</a>'
            });
        },
        positionPopup() {
            this.$swal({
                position: 'top-end',
                type: 'success',
                title: 'Data is saved in Database',
              showConfirmButton: false,
              timer: 1000
            });
        },
        deletePopup() {
            this.$swal({
                  title: "Do you want to delete this record",
                  text: "This will be record from Database",
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#4026e3",
                  confirmButtonText: "Yes, remove it it!"
                  }).then((result) => { // <--
                  if (result.value) { // <-- if accepted
                          del('status-delete/' + id);
                          }
                  });
        },
          AlertPassingData() {
            this.$swal({
              title: 'Please enter String?',
              input: 'text',
              inputPlaceholder: 'Enter String here',
              showCloseButton: true,

            });
        },
    }
  }
</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>
Output is
vue sweetalert input dialog examples

Placing Html content 

The alert dialog can also provide static content and dynamic content. Dynamic content can be placed using HTML attribute of $swal function. Can also contain HTML custom forms to take input from user Here is an example for HTML content in the Dialog window
<button v-on:click="htmlContentAlert ">Html contentPopup</button>
 htmlContentAlert {
            this.$swal({
   title: "<i>This is title</i>", 
   html: "This is html text: <b>bold</b><i> italic</i>",  
   confirmButtonText: "V <u>Yes</u>", 
});;
},

Ajax demo usage 

This is an example for ajax for asynchronous processing of a request. This shows on loading icon image on loading ajax request processing

   <button v-on:click="ajaxAlert">Ajax Popup</button>

  ajaxAlert() {
            this.$swal({
  title: "Asynchronus example",
  text: "Demo application for ajax example",
  type: "info",
  showCancelButton: true,
  closeOnConfirm: false,
  showLoaderOnConfirm: true
}, function () {
  setTimeout(function () {
    swal("Completed!");
  }, 2000);
});
        },
  
The code for this blog post can be download from here

Related article


EmoticonEmoticon