Introduction
In this article, we will learn how to use sweetalert2 in Vue.js Application.sweetalert2 used to display an alert and notification message.
Prerequisites
- Basic Knowledge of Vue.js
- Visual Studio Code
- Node and NPM installed
- Bootstrap
Create VueJS Project
Create a Vue.js project by using the following command.
vue create myalertapp
Open the newly created project in Visual Studio code and Install vue-sweetalert2 package by using the following command:
npm install -S vue-sweetalert2
Install bootstrap by using following command.
npm install bootstrap
Now open the main.js file and add following code.
import Vue from 'vue'
import App from './App.vue'
import VueSweetalert2 from 'vue-sweetalert2';
import 'bootstrap/dist/css/bootstrap.css'
import 'sweetalert2/dist/sweetalert2.min.css';
Vue.config.productionTip = false
Vue.use(VueSweetalert2);
new Vue({
render: h => h(App),
}).$mount('#app')
Now open Helloworld.vue component and add the following code.
<template>
<div class="container">
<div class="large-12 medium-12">
<div style="margin: 20px;" class="col-sm-12 btn btn-info"> Sweetalert in Vue.js </div>
<button style="margin: 10px;" class="btn btn-info" v-on:click="showAlert">Alert</button>
<button style="margin: 10px;" class="btn btn-info" v-on:click="showAlertConfirm">Confirm</button>
<button class="btn btn-warning" v-on:click="alertDisplay">Custom Design</button>
</div>
</div>
</template>
<script>
export default {
methods: {
showAlert(){
this.$swal('Hello world!!!');
},
showAlertConfirm(){
this.$swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d13737',
confirmButtonText: 'Yes, Delete'
}).then((result) => {
if (result.value) {
this.$swal(
'Deleted!',
'Your Data has been deleted.',
'Success'
)
}
});
},
alertDisplay() {
this.$swal({
title: '<i>Custom Design</i>',
html:
'Hello C# Corner ' ,
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
})
}
}
}
</script>
Now run the application by using following command.
npm run serve
![]()
Now click on the button and check
![]()
![]()
Summary
In this article, we learned how to use sweetalert2 in Vue.js applications.